How do I avoid Latch in Verilog ?

| Saturday, August 29, 2009


Latches are always bad (I don't like that statement); latches are caused when all the possible cases of assignment to variable are not covered. Well this rule applies to combinational blocks (blocks with edge sensitive lists are sequential blocks); let's look at the following example.

Bad Code

 1  always @ (b or c)
 2  begin
 3    if (b) begin
 4      a = c;
 5    end
 6  end

In the code above, value of a is retained, and it gets changed only when b is set to '1'. This results in a latch. (Need to phrase it right)

Good Code #1

 1  always @ (b or c)
 2  begin
 3    a = 0;
 4    if (b) begin
 5      a = c;
 6    end
 7  end

In the code above, no matter what the value of b is, a gets value of '0' first and if b is set to '1' and c is set to '1', only then a gets '1'. This is the best way to avoid latches.

Good Code #2

 
 1  always @ (b or c)
 2  begin
 3    if (b) begin
 4      a = c;
 5    end else begin
 6      a = 0;
 7    end
 8  end

In the above code, all the possible cases are covered (i.e. b = 1 and b = 0 case).

0 comments:

Post a Comment