# Counter Design using verilog HDL

• Difficulty Level : Easy
• Last Updated : 13 Jun, 2022

Prerequisite – Counters in Digital Logic

Problem :
Design 4 bit up-down synchronous counter  Verilog Hardware Description Language along with Testbench

Design Specification :

Block diagram of design requirements : 4-bit counter

The counter is a digital sequential circuit and here it is a 4 bit counter, which simply means it can count from 0 to 15 and vice versa based upon the direction of counting (up/down).

• The counter (“count“) value will be evaluated at every positive (rising) edge of the clock (“clk“) cycle.
• The Counter will be set to Zero when “reset” input is at logic high.
• The counter will be loaded with “data” input when the “load” signal is at logic high. Otherwise, it will count up or down.
• The counter will count up when the “up_down” signal is logic high, otherwise count down.

Verilog HDL Code :

Design –

```// Here we will learn to write a verilog HDL to design a 4 bit counter
//define input and output ports
input [3:0] data;
output reg [3:0] count;
//always block will be executed at each and every positive edge of the clock
always@(posedge clk)
begin
if(reset)    //Set Counter to Zero
count <= 0;
count <= data;
else if(up_down)        //count up
count <= count + 1;
else            //count down
count <= count - 1;
end
endmodule :counter```

Testbench :

```// Code your testbench here
module counter_tb;
reg [3:0] data;
wire [3:0] count;
// instance counter design
counter ct_1(.ud(up_down),.*);
//clock generator
initial begin clk = 1'b0; repeat(30) #3 clk= ~clk;end
//insert all the input signal
initial begin reset=1'b1;#7 reset=1'b0; #35 reset=1'b1;end
initial begin #5 ud=1'b1;#24 ud=1'b0;end
initial begin data=4'b1000;#14 data=4'b1101;#2 data=4'b1111;end
//monitor all the input and output ports at times when any inputs changes its state
endmodule :counter_tb```

Expected Output :

```time=0,reset=1,load=x,ud=x,data= 8,count= x