VHDL For Loops
for Current_Range in Range_Start to Range_End loop
new_signal(Current_Range) <= '1';
Keep in mind that the above code is pointless since you could simply do this instead:
new_signal <= (others => '1');
So let's see why we would want to use for loops next.
The purpose of the for loop in VHDL is to give you the ability to have a repeating loop that can be set to be implemented a discrete number of times. Unlike software, the for loop here is actually creating hardware implementations. So you need to be careful in how you use it because in FPGA land, we have limited hardware resources.
Because VHDL is so strict on type, usually for known designs where the width of signals is solid you may not need to ever use for loops. However, there are 2 very common reasons to use them:
1. When designing for re-usable code, for loops are an advanced way for the designer to make very modular code that can be quickly adapted to different signal widths. Here you can tie the range start and range end to either constants or better yet generics that can be changed quickly to alter the design.
2. It's a great way to create the same hardware design in a few lines of code where the alternative would require a ton of code for an equivalent design.
In this example, we have an enable for each bit on a 64 bit bus, and if the enable is '1', then we pass the bus bit from input to output. If the enable is '0', we set the output bus bit to '0'. Basically, we are anding each input bus bit with the enable bit to create the output bus. This would take a ton of code to do without the for loop.
for i in 0 to 63 loop
output_bus(i) <= input_bus(i) and bus_en(i);
Which can be written this way too:
for i in 0 to 63 loop
if bus_en(i) = '1' then
output_bus(i) <= input_bus(i);
output_bus(i) <= '0';
1. For loops can be tricky depending on how you write them. Be sure to add comments on exactly what the goal is and how it works so that when you revisit your code later or if someone else needs to edit your code that it's easy to understand what's going on.
2. Be careful and aware of what the for loop is doing so that you aren't creating a design that uses a lot of resources needlessly.
3. Weigh the benefit of using for loops instead of long written code (15 lines or more) where for loops may make more sense and can be done in only a few lines.
4. Always shoot for re-usable code on common parts of the design, such that if you can have 1 design work for many situations, then consider for loops with generics driving the range so that it's easy to use the same design for multiple things.
5. Don't use for loops to look cute or advanced. Use regular and more common code most of the time when appropriate. Not everyone that will edit your code is a master and if they can't make your design work for something new, your design will die.
6. In my experience, I've probably used for loops 1% of the time. There needs to be a big savings in code to justify it.