Which is a better method of designing an upcounter in verilog from the ones mentioned below?

StackOverflow https://stackoverflow.com/questions/23356834

  •  11-07-2023
  •  | 
  •  

Question

I have declared an 8 bit register variable count

reg [7:0]count=0;

count is supposed to increment from 8'h00 to 8'hFF & back to 8'h00 & increment again so on.
Below i am providing 2 ways of doing this

always @(posedge Clk)  
   begin  
      if(count==8'hFF)  
         count<=8'h0;  
      else  
         count<=count+1;  
   end 

OR

always @(posedge Clk)  
   begin  
     count<=count+1;  
   end

In the 1st case, count will go from 00 to FF & 00 to FF again & again.
In the 2nd case also, count will go from 00 to FF then overflow to 00 with a carry & increment to FF again & again.

Will that carry affect anything & how? Also which method is better synthesis wise?

Was it helpful?

Solution

Either method will work. The best result is dependent on the how smart/dump your synthesizing tool is. Some tools issue warnings when it sees an overflow is possible. If you want to resolve the warning, you can use the below method:

reg [7:0] count = 0;
wire [8:0] next_count = count + 1'b1; // MSB is overflow bit
always @(posedge Clk)
  count <= next_count[7:0]; // overflow bit not used in assignment

The overflow bit could be done in the synchronous block. Unless you plan on using the overflow bit, I would not recommend these as it will either waste a flop (dumb synthesizer) or issue a warning that a flop has been optimized out (smart synthesizer).

reg [7:0] count = 0;
reg overflow;
always @(posedge Clk)
  {overflow,count} <= count + 1'b1; // optimization warning OR wasted flop

OTHER TIPS

According to IEEE Std 1364™-2005

should an arithmetic add of two 16-bit values perform the evaluation using 16 bits, or should the evaluation use 17 bits in order to allow for a possible carry overflow? The answer depends on the type of device being modeled and whether that device handles carry overflow. The Verilog HDL uses the bit length of the operands to determine how manybits to use while evaluating an expression. The bit length rules are given in 5.4.1. In the case of the addition operator, the bit length of the largest operand, including the lefthand side of an assignment, shall be used

They have given an example which I think is applicable for this case:

reg[15:0] a, b; // 16-bit regs
reg[15:0] sumA; // 16-bit reg
reg[16:0] sumB; // 17-bit reg
sumA = a + b; // expression evaluates using 16 bits
sumB = a + b; // expression evaluates using 17 bits

So, hopefully it won't affect the synthesis and is better than previous one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top