Digital Counters
From simple binary counting to glitch-free Gray codes and shift-register based counters.
1. Gray Counter (Glitch Free)
Why? Used in Async FIFOs because only 1 bit changes at a time. This prevents metastable errors when sampling across clock domains.
Verilog: Binary to Gray
module gray_counter (
input clk, rst_n,
output reg [3:0] gray_out
);
reg [3:0] bin_cnt;
always @(posedge clk or negedge rst_n) begin
if (!rst_n) begin
bin_cnt <= 0;
gray_out <= 0;
end else begin
bin_cnt <= bin_cnt + 1;
// Conversion: Gray = (Binary >> 1) ^ Binary
gray_out <= (bin_cnt >> 1) ^ bin_cnt;
end
end
endmodule
2. Ring vs Johnson Counter
Ring Counter
A shift register where the output of the last flip-flop feeds the input of the first.
Sequence (4-bit): `1000` -> `0100` -> `0010` -> `0001` -> `1000`.
- States: N states for N flops.
- Usage: One-hot encoding for state machines.
Johnson Counter (Twisted Ring)
Output of last flop is inverted before feeding the first.
Sequence (4-bit): `0000` -> `1000` -> `1100` -> `1110` -> `1111` -> `0111`...
- States: 2N states for N flops.
- Pros: More states per flop than Ring, but requires decoding logic.