## Ring Counter

4 bit ring counter is a circuit that counts in the fashion shown below
``````
0001
0010
0100
1000
0001
..
..
and so on
``````
` `

At the time of reset the value of the counter is initialized to, say, 0001. It then becomes 0010 at the next clock cycle - and this keeps going on. Basically there is one bit that keeps shifting to left 1 bit at each clock cycle and then it rolls over when it reaches MSB. Here is the verilog implemmentation of ring counter.

 `// referencedesigner.com // 4 bit ring counter example module four_bit_ring_counter ( input clock, input reset, output [3:0] q );  reg[3:0] a;  always @(posedge clock) if (reset) a = 4'b0001;  else begin a <= a<<1; // Notice the blocking assignment a<=a; end  assign q = a;  endmodule`

## Some Explanation

At the time of reset we make the ring counter to start at 4'b0001;

 `a = 4'b0001;`

When it comes out of reset, we use two statements to update the ring counter at each cycle.

 ```a <= a<<1; // Notice the blocking assignment a <= a;```

Notice that we have used non blocking assignment and not blocking assignment. You can think of it as follows. Just before the clock cycle, mentally calculate a<<1 in a temporary register. Also mentally assign a the value of a, BEFORE the execution of the a<<1. Now at the rising edge of the clock the two assignmenta take place.

For example let us say current value of a is 0010. The the left shift assignment will shift it to 0100. The a <= a will not change anything.

Now when the value of the a is 1000, then we have to be careful. The left shift a<<1 assignment is tending to make a to 4'b0000. But remember, we have used non blocking assignment. So the next non blocking statement a <= a takes effect. This statememt, takes the value of a which is 1'b1. Now mentally store is in your mind and at the next clock cycle assign it to a.

If, however, you use blocking assignment staatements like

 ```a = a<<1; a = a```

Then counting from 4'b1000 to 4'b0000 may have an issue, and the simulator may result in rolling over to 4'b0000

Here is a test bench for the ring counter.

 ``timescale 1ns / 1psmodule stimulus; // Inputs reg clock; reg reset; // Outputs wire[3:0] q; // Instantiate the Unit Under Test (UUT) four_bit_ring_counter r1 ( .clock(clock), .reset(reset), .q(q) );  always #10 clock = ~clock;  initial begin // Initialize Inputs clock = 0; reset = 0;  #5 reset = 1; #20 reset = 0; #500 \$finish; end   initial begin \$monitor(\$time, " clock=%1b,reset=%1b,q=%4b",clock,reset,q); end endmodule`