Verilog Code for Johnson Counter: Syntax and Example
A
Johnson counter in Verilog is a shift register where the inverted output of the last flip-flop is fed back to the first. It cycles through a sequence of states twice the length of the register. The code uses a clock, reset, and a register to implement this behavior.Syntax
The Johnson counter uses a register to hold the state bits. On each clock edge, the register shifts left, and the inverted last bit is fed back to the first bit. A synchronous reset sets the register to zero.
- clk: Clock input to trigger state changes.
- reset: Synchronous reset to initialize the counter.
- q: Output register holding the current state.
verilog
module johnson_counter(
input wire clk,
input wire reset,
output reg [3:0] q
);
always @(posedge clk) begin
if (reset) begin
q <= 4'b0000;
end else begin
q <= {~q[0], q[3:1]};
end
end
endmoduleExample
This example shows a 4-bit Johnson counter. It cycles through 8 unique states by shifting bits and feeding back the inverted last bit. The output q changes on every clock pulse, and resets to zero when reset is high.
verilog
module testbench();
reg clk = 0;
reg reset = 1;
wire [3:0] q;
johnson_counter uut (
.clk(clk),
.reset(reset),
.q(q)
);
always #5 clk = ~clk; // Clock with 10 time units period
initial begin
$monitor($time, " ns: q = %b", q);
#10 reset = 0; // Release reset after 10 time units
#80 $finish; // Run simulation for 80 time units
end
endmoduleOutput
10 ns: q = 0000
20 ns: q = 1000
30 ns: q = 1100
40 ns: q = 1110
50 ns: q = 1111
60 ns: q = 0111
70 ns: q = 0011
80 ns: q = 0001
90 ns: q = 0000
Common Pitfalls
Common mistakes include:
- Feeding back the wrong bit (should be the inverted least significant bit).
- Using asynchronous reset instead of synchronous, which can cause glitches.
- Not initializing the register properly, leading to unknown states.
Always ensure the feedback bit is ~q[0] and the shift is done correctly.
verilog
/* Wrong feedback example (incorrect bit fed back) */ q <= {~q[3], q[3:1]}; // Incorrect: feedback should be inverted q[0] /* Correct feedback example */ q <= {~q[0], q[3:1]};
Quick Reference
- Use a register of size
nbits for ann-bit Johnson counter. - On each clock, shift left and feed back the inverted last bit.
- Synchronous reset sets the register to zero.
- The Johnson counter cycles through
2nunique states.
Key Takeaways
A Johnson counter shifts bits and feeds back the inverted last bit to create a 2n-state cycle.
Use synchronous reset to initialize the counter safely.
Ensure feedback uses the inverted least significant bit, not other bits.
The output register size determines the number of states (2 times the register length).
Test your design with a simple testbench to verify correct state transitions.