Thursday, April 23, 2020

3-Bit Up Counter Verilog Code

A counter is necessary for any timing operation in a design. Let us see how to design a 3-bit counter and then parametrize it to obtain an n-bit counter.


Design Problem:
Let us design a 3-bit up counter using D-Flip Flops.
We must start from 000 and increment by 1 every clock cycle. Reset back to 000 after reaching 111 and continue couting as long as clock is supplied.
Inputs: clk, rst
Outputs: cnt

Logic:
Use an internal variable next_cnt that increments cnt by 1. At every clock cycle, cnt gets the value of next_cnt using D Flip-Flops.

Verilog Code:


module counter(cnt,clk,rst);
input clk,rst;
output [2:0]cnt;

reg [2:0]cnt;
wire [2:0]next_cnt;

assign next_cnt = cnt + 1'b1;  //Just increment by 1

always @ (posedge clk or negedge rst)   
begin
 if(!rst)
 begin
 cnt <= 3'b0;
 end
 else
 begin
 cnt <= next_cnt;
 end
end

endmodule

Testbench:

module counter_tb;
 reg clk;
 reg rst;
 wire [2:0] cnt;

 counter uut (
  .cnt(cnt), 
  .clk(clk), 
  .rst(rst)
 );

 always #5 clk = ~clk;
 
 initial begin
  clk = 1'b0;
  rst = 1'b0;
  #20 rst = 1'b1;
  #200 $finish;
 end
endmodule

Simulation Result:
3-bit counter simulation waveform

As can be seen in the waveform, the counter starts counting after coming out of reset state from 000 to 111. After this, it resets back to 000 and starts counting again.

To design an n-bit counter, change the number of bits of next_cnt and cnt to n-bits. Also instantiate as many number of D Flip-Flops. You can use parameter for specifying number of bits. Check out the last section of Verilog Tutorial 5 to see how this is done.

No comments:

Post a Comment