Skip to content
Related Articles

Related Articles

Counter Design using verilog HDL

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 13 Jun, 2022
View Discussion
Improve Article
Save Article

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
module counter(clk,reset,up_down,load,data,count);
  //define input and output ports
  input clk,reset,load,up_down;
  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) 
    if(reset)    //Set Counter to Zero
      count <= 0;
    else if(load)    //load the counter with data value
      count <= data;
    else if(up_down)        //count up
      count <= count + 1;
    else            //count down
      count <= count - 1;
endmodule :counter

Testbench :

// Code your testbench here
module counter_tb;
  reg clk,reset,load,ud;
  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 #12 load=1'b1; #5 load=1'b0;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
  initial begin $monitor("time=%0d,reset=%b,load=%b,ud=%b,data=%d,count=%d",
endmodule :counter_tb

Expected Output :

time=0,reset=1,load=x,ud=x,data= 8,count= x
time=3,reset=1,load=x,ud=x,data= 8,count= 0
time=5,reset=1,load=x,ud=1,data= 8,count= 0
time=7,reset=0,load=x,ud=1,data= 8,count= 0
time=9,reset=0,load=x,ud=1,data= 8,count= 1
time=12,reset=0,load=1,ud=1,data= 8,count= 1
time=14,reset=0,load=1,ud=1,data=13,count= 1
time=45,reset=1,load=0,ud=0,data=15,count= 0

Note : Follow this link to online simulate this design.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!