Verilog Coding Tips and Tricks: Verilog code for Up/Down Counter using Behavioral modelling

Monday, October 26, 2015

Verilog code for Up/Down Counter using Behavioral modelling

An up/down counter is a digital counter which can be set to count either from 0 to MAX_VALUE or MAX_VALUE to 0. The direction of the count(mode) is selected using a single bit input.

In this post, I have shared the Verilog code for a 4 bit up/down counter. The module has 3 inputs - Clk, reset which is active high and a UpOrDown mode input. The output is Counter which is 4 bit in size.

4 bit UP/DOWN Counter:

//Verilog module for UpDown counter
//When Up mode is selected, counter counts from 0 to 15 and then again from 0 to 15.
//When Down mode is selected, counter counts from 15 to 0 and then again from 15 to 0.
//Changing mode doesn't reset the Count value to zero.
//You have apply high value to reset, to reset the Counter output.
module upordown_counter(
    Clk,
    reset,
    UpOrDown,  //high for UP counter and low for Down counter
    Count
    );

    
    //input ports and their sizes
    input Clk,reset,UpOrDown;
    //output ports and their size
    output [3 : 0] Count;
    //Internal variables
    reg [3 : 0] Count = 0;  
    
     always @(posedge(Clk) or posedge(reset))
     begin
        if(reset == 1) 
            Count <= 0;
        else    
            if(UpOrDown == 1)   //Up mode selected
                if(Count == 15)
                    Count <= 0;
                else
                    Count <= Count + 1; //Incremend Counter
            else  //Down mode selected
                if(Count == 0)
                    Count <= 15;
                else
                    Count <= Count - 1; //Decrement counter
     end    
    
endmodule

Testbench for counter:

module tb_counter;

    // Inputs
    reg Clk;
    reg reset;
    reg UpOrDown;

    // Outputs
    wire [3:0] Count;

    // Instantiate the Unit Under Test (UUT)
    upordown_counter uut (
        .Clk(Clk), 
        .reset(reset), 
        .UpOrDown(UpOrDown), 
        .Count(Count)
    );

//Generate clock with 10 ns clk period.
    initial Clk = 0;
    always #5 Clk = ~Clk;
    
    initial begin
        // Apply Inputs
        reset = 0;
        UpOrDown = 0;
        #300;
        UpOrDown = 1;
      #300;
        reset = 1;
        UpOrDown = 0;
        #100;
        reset = 0;  
    end
      
endmodule

Simulation waveform:

The codes when simulated correctly, will show the following waveform in Xilinx ISE 13.1

No comments:

Post a Comment