Verilog for loop

if you are familar with C background, you will notice two important differences in verilog. The firs one has to do with the for loop itself - we have begin and end in place of { and }. Secondly, statements like i++ are not allowed, we have to write instead as i = i+1;

Make use of for loop freely in test benches. Instead of linearly specifying the stimulus, use for loop to go through a set of values.

We will now see how the us of for loop simplifies the test bench. Let us take a look at the priority encoder example.
  1. // Referencedesigner.com
  2. // Priority Encoder Example - Usage of case
  3. // Verilog Tutorial
  4.  
  5. module priory_encoder_case
  6. (
  7. input wire [4:1] x,
  8. output reg [2:0] pcode
  9. );
  10. always @ *
  11.  
  12. case (x)
  13. 4'b1000, 4'b1001 , 4'b1010, 4'b1011 , 4'b1100 , 4'b1101, 4'b1110 , 4'b1111 :
  14. pcode = 3'b100;
  15. 4'b0100, 4'b0101 , 4'b0110, 4'b0111 :
  16. pcode = 3'b011 ;
  17. 4'b0010, 4'b0011 :
  18. pcode = 3'b010;
  19. 4'b0001 :
  20. pcode = 3'b001;
  21. 4'b0000 :
  22. pcode = 3'b000;
  23. endcase
  24.  
  25. endmodule


Note that the always statement always @(x[4], x[3],x[2], x[1]) Could be written as always @ * We now suggest that you write a test bench for this code and verify that it works. If you have sifficulty, you can check it with following test bench

  1.  
  2. `timescale 1ns / 1ps
  3. module stimulus;
  4. reg [4:1] x;
  5. wire [2:0] pcode;
  6. // Instantiate the Unit Under Test (UUT)
  7. priory_encoder_case uut (
  8. .x(x),
  9. .pcode(pcode)
  10. );
  11.  
  12. initial begin
  13. // Initialize Inputs
  14. x = 4'b0000;
  15.  
  16. #20 x = 4'b0001;
  17. #20 x = 4'b0010;
  18. #20 x = 4'b0011;
  19. #20 x = 4'b0100;
  20. #20 x = 4'b0101;
  21. #20 x = 4'b0110;
  22. #20 x = 4'b0111;
  23. #20 x = 4'b1000;
  24. #20 x = 4'b1001;
  25. #20 x = 4'b1010;
  26. #20 x = 4'b1011;
  27. #20 x = 4'b1100;
  28. #20 x = 4'b1101;
  29. #20 x = 4'b1110;
  30. #20 x = 4'b1111;
  31. #40 ;
  32.  
  33. end
  34.  
  35. initial begin
  36. $monitor("t=%3d x=%4b,pcode=%3b",$time,x,pcode );
  37. end
  38.  
  39. endmodule
  40.  
  41.  


The test bench could be written as

  1.  


Notice that the code gets simplified. Few things to be careful about in this code are 1. If instead of
	for (x=0; x < 15; x= x+1)

we write
	for (x=0; x <= 15; x= x+1)

it will create an infinite loop as x wraps from 15 to 0 ( since it is defined as 5 bit). Also notice that we need to explicitly declare and statement using ;. Finally, we could omit the begin and end since we have only one statement to execute. So instead of


	for (x=0; x < 15; x= x+1)
	begin
	#20 ;
	end // end of for loop 
	



We could write
	for (x=0; x < 15; x= x+1)
	#20 ; // end of for loop 
	

Care must be taken when for loop is used in the synthesisable verilog code. We will cover it as in comes in other examples. For now we are just learning the for loop constructs.