While Loop – Verilog Example

Use while loops in your simulation testbench

While loops are used in software languages often to run some code for an indeterminate amount of time. A while loop does some action until the condition it is checking is no longer true. While loops are a part of Verilog, however I do not recommend using while loops for synthesizable code.

The reason that while loops do not belong in synthesizable code is that when the synthesis tool tries to turn your code into gates and registers it needs to know exactly how many times the loop will run. It will only expand replicated logic a determinate number of times. When you know exactly how many times a loop will run, you’re really talking about a for loop. For that reason, stick to for loops to expand your replicated logic for synthesis.



While Loops in Simulation

While loops can be very useful in your testbenches! When some code needs to run an indeterminate amount of loops, a while loop can do the job! While loops can be put into tasks to perform some action again and again in your code. Note that Verilog does not support do while but System Verilog does.. Also, note that the Jump Statements return and break can be used to exit your loop prematurely, but these are only supported in SystemVerilog.

while_example.v:

module while_example (); 
  integer ii=0;
  reg [7:0] r_Data[15:0]; // Create reg 8 bit wide by 16 words deep.
  
  initial 
    begin
      
      // Sets first value of r_Data to allow while loop to execute
      // (Allows it to be true on the first iteration)
      r_Data[ii] = ii*ii;
      
      while (r_Data[ii] < 100)  
        begin
          $display("Time %2d: r_Data at Index %1d is %2d", $time, ii, r_Data[ii]);
          ii = ii + 1;
          r_Data[ii] = ii*ii;
          #10;
        end
    end
endmodule 

 

Console Result from Modelsim Simulation:
# Time  0: r_Data at Index 0 is  0
# Time 10: r_Data at Index 1 is  1
# Time 20: r_Data at Index 2 is  4
# Time 30: r_Data at Index 3 is  9
# Time 40: r_Data at Index 4 is 16
# Time 50: r_Data at Index 5 is 25
# Time 60: r_Data at Index 6 is 36
# Time 70: r_Data at Index 7 is 49
# Time 80: r_Data at Index 8 is 64
# Time 90: r_Data at Index 9 is 81

Note that in the example above, we had to set the first value of r_Data[0] to allow the first iteration of the while loop to execute. If the first check of the while loop is not true, then the loop will never run. A do-while loop avoids the requirement that the first check is true, but this is only supported with SystemVerilog.

Learn Verilog

Modules

Learn VHDL