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(
    Clock,
    Reset,
    Count_out
    );

    //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)
    begin
        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 
    end
    
    //The Count value is assigned to final output port.
    assign Count_out = Count_temp;
    
endmodule

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(Clock), 
        .Reset(Reset), 
        .Count_out(Count_out)
    );

    ///////////////////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.
    end
      
endmodule

Simulation Waveform:

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


4 comments:

  1. How to assign input in simulation window
    Send me Please sir

    ReplyDelete
    Replies
    1. you cant do it in simulation window.But write a testbench code and assign the inputs there. try it. its very easy and very useful. see this video: https://youtu.be/euk7iiiBDBE

      Delete