Verilog Always block


Always block

An always block is used to execute a block of statements depending upon if the values of any of the inputs to the block ( called a sensitivity list) changes.

As usual we will first give an example and then give explanation. Let us rewrite the 1 bit comparator we had studied earlier, using always block.

  1. module comparator(
  2. input x,
  3. input y,
  4. output reg z
  5. );
  6.  
  7. reg p,q;
  8. always @(x,y)
  9. begin
  10.  
  11. p = (~x & ~y);
  12. q = x & y;
  13.  
  14. z = p |q;
  15. end
  16.  
  17. endmodule


We have used always block as follows

always @(x,y);

This essentially means that the code follwed by always statement will run ONLY when the values of the variable x or y changes. We can have more than two variables in the sensitivity list.

One more thing to notice is that the output z has been assigned a reg and not a wire. However, this register will not be really synthesezes to actual register since its value is simple assignment statement depending upon two inputs.

A register variable in verilog simply means a variable that can "hold" value.

The statements in the assigment block are executed sequentially and order does matter. So we will have to be careful about the order.

Multiple statements within the always block are surrounded by begin and end.

The assign statement could also be used as always @*

The stimulus block stays the same and it is being reproduced below.

  1.  
  2. `timescale 1ns / 1ps
  3. module stimulus;
  4. // Inputs
  5. reg x;
  6. reg y;
  7. // Outputs
  8. wire z;
  9. // Instantiate the Unit Under Test (UUT)
  10. comparator uut (
  11. .x(x),
  12. .y(y),
  13. .z(z)
  14. );
  15.  
  16. initial begin
  17. $dumpfile("test.vcd");
  18. $dumpvars(0,stimulus);
  19. // Initialize Inputs
  20. x = 0;
  21. y = 0;
  22.  
  23. #20 x = 1;
  24. #20 y = 1;
  25. #20 y = 0;
  26. #20 x = 1;
  27. #40 ;
  28.  
  29. end
  30.  
  31. initial begin
  32. $monitor("t=%3d x=%d,y=%d,z=%d \n",$time,x,y,z, );
  33. end
  34.  
  35. endmodule
  36.  
  37.  


As usual we get the following result when we compile and run it.
 


t=  0 x=0,y=0,z=1

t= 20 x=1,y=0,z=0

t= 40 x=1,y=1,z=1

t= 60 x=1,y=0,z=0





The verilog always statement could also be written as

always @( a or b or c)

which is equivalent to

always @( a , b , c)

Thumb Rule for always block in combinatorial block In order to create Verilog code that can generate synthesizable circuit, all inputs to the hardware must appear in the sensitivity list. If it does not, then a latch will result in place of a combinatorial logic.

Exercise
1. Extend the full adder example presented earlier using always block. Check it using the same stimulus.