Verilog Coding Tips and Tricks: Verilog Code for 4 bit Ring Counter with Testbench

Monday, October 19, 2015

Verilog Code for 4 bit Ring Counter with Testbench

 A ring counter is a digital circuit with a series of flip flops connected together in a feedback manner.The circuit is special type of shift register where the output of the last flipflop is fed back to the input of first flipflop.When the circuit is reset, except one of the flipflop output,all others are made zero. For n-flipflop ring counter we have a MOD-n counter. That means the counter has n different states.
The circuit diagram for a 4 bit ring counter is shown below:

   I have written a Verilog code for a 4-bit ring counter which has the following states:
0001  -   0010   -  0100   -   1000 .... and so on

4 bit Ring Counter:

//declare the Verilog module - The inputs and output port names.
module ring_counter(

    //what are the input ports and their sizes.
    input Clock;
    input Reset;
    //what are the output ports and their sizes.
    output [3:0] Count_out;
    //Internal variables
    reg [3:0] Count_temp;

    //Whenever the Clock changes from 0 to 1(positive edge) or 
    //a change in Reset, execute the always block.
    always @(posedge(Clock),Reset)
        if(Reset == 1'b1)   begin  //when Reset is high 
            Count_temp = 4'b0001;   end  //The Count value is reset to "0001".
        else if(Clock == 1'b1)  begin  //When the Clock is high
            //Left shift the Count value.
            Count_temp = {Count_temp[2:0],Count_temp[3]};   end 
    //The Count value is assigned to final output port.
    assign Count_out = Count_temp;

Testbench for Ring Counter:

module tb_ring;

    // Inputs
    reg Clock;
    reg Reset;

    // Outputs
    wire [3:0] Count_out;

    // Instantiate the Unit Under Test (UUT)
    ring_counter uut (

    ///////////////////Clock generation ///////////////////////////
    initial Clock = 0; 
    always #10 Clock = ~Clock; 
    ////////// #10 means wait for 10 ns before executing the next statement. ///////////
    //Simulation inputs.
    initial begin
    //Apply Reset for 50 ns.
        Reset = 1; //Reset is high
        #50;       //Wait for 50 ns
        Reset = 0; //Reset is low.

Simulation Waveform:

When the codes are correctly simulated you should get the following waveform. I have used Xilinx ISE 13.1 for this.

No comments:

Post a Comment