Verilog Coding Tips and Tricks: Verilog code for 4 bit Johnson Counter with Testbench

Monday, October 19, 2015

Verilog code for 4 bit Johnson Counter with Testbench

 A Johnson 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 complement output of the last flipflop is fed back to the input of first flipflop.This is almost similar to ring counter with a few extra advantages.When the circuit is reset all the flipflop outputs are made zero. For n-flipflop Johnson counter we have a MOD-2n counter. That means the counter has 2n different states.
The circuit diagram for a 3 bit Johnson counter is shown below:

I have written a Verilog code for a 4-bit Johnson counter which has the following states:
0000  -   0001   -  0011   -   0111  -  1111  -  1110  -  1100  -  1000   -  0000 .... and so on

4 bit Johnson Counter:

//declare the Verilog module - The inputs and output port names.
module johnson_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) or Reset)
        if(Reset == 1'b1)   begin  //when Reset is high 
            Count_temp = 4'b0000;   end  //The Count value is reset to "0000".
        else if(Clock == 1'b1)  begin  //When the Clock is high
            //Left shift the Count value and at the same time
            //negate the least significant bit.
            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 Johnson Counter:

You can use the same testbench I have written for Ring counter for simulating the Johnson counter too. But you have to make a small change. Change the uut name into the one for Johnson code.

Simulated Waveform:

The codes, when properly simulated will give the following waveform in Xilinx ISE 13.1.

No comments:

Post a Comment