A Gray counter, also called a reflected binary counter or Gray code counter, steps through all 2N states of an N-bit register like a binary counter, but changes only one bit on each clock edge. In Verilog, a Gray counter is usually built as a binary counter whose value is converted to Gray code with XOR gates and stored in a register.

12 min read | Beginner Level

What You'll Learn

  • Why a single-bit change per count avoids glitches and sampling errors
  • Write a parameterized Gray counter using a binary counter and an XOR conversion
  • How Gray counters are used in asynchronous FIFOs, encoders and ADCs
  • The timing cost of Gray-to-binary conversion, and common Gray counter mistakes

What is a Gray Counter ?

A Gray counter goes through the same number of states as a binary counter of the same width, but in a different order. Each value in the sequence differs from the one before it, and from the one after it, in exactly one bit. This also holds at the wrap-around from the last value back to the first. See Verilog Binary to Gray for the code conversion itself.

CountBinaryGrayGray (hex)
0000000000
1000100011
2001000113
3001100102
4010001106
5010101117
6011001015
7011101004
810001100c
............
15111110008

From count 7 to 8, the binary value changes in all four bits, while the Gray value changes only in bit 3. The conversion from binary b to Gray g is a single XOR per bit:

g = b ^ (b >> 1)      // g[N-1] = b[N-1],  g[i] = b[i+1] ^ b[i]
Binary and Gray code values from count 6 to 9 with the changed bits highlighted

The Problem Gray Code Solves

Consider a 3-bit binary counter going from 011 (3) to 100 (4). All three bits change on the same clock edge, but in real hardware they never change at exactly the same instant: each flip-flop and each wire has a slightly different delay. For a short time, the outputs can show values such as 111 or 000 that the counter never actually holds.

Logic that watches the count, such as a decoder, a comparator or a state machine, can react to these brief false values and produce glitches or wrong decisions. A circuit in another clock domain that samples the count at that moment can capture a value that is far from both the old and the new count.

A Gray counter avoids this, because only one bit is ever in transition. While it changes, the value is either the old count or the new count, never anything else.

Quick Check

Q: Another clock domain samples a Gray counter just as it changes from 0100 (count 7) to 1100 (count 8). Which values can it capture?

Show Answer

Only 0100 or 1100, which are counts 7 and 8. Bit 3 is the only bit that changes, so whichever value of bit 3 is captured, the result is a valid neighbor. A binary counter sampled during its 7 to 8 transition could produce any of the 16 values.

Where Gray Counters are used ?

The single-bit-change property matters wherever a count is read without a guarantee that all its bits have settled.

Asynchronous FIFOs (the most important use case)

An asynchronous FIFO has a write side and a read side running on unrelated clocks. To decide whether the FIFO is full or empty, each side needs to know the other side's pointer, which means passing a multi-bit counter between clock domains. If a binary pointer is sampled while several of its bits are changing, the receiving side can see a completely wrong value. A Gray-coded pointer, passed through a two-flip-flop synchronizer, can only be seen as its old or its new value, so the worst case is a full or empty flag that is one cycle late, which is safe. Practically every well-designed asynchronous FIFO uses Gray pointers. How full and empty are computed from Gray pointers is an advanced topic beyond this article.

Rotary encoders and shaft position sensing

Absolute position encoders use a disc or strip marked with a Gray code pattern, read by optical or magnetic sensors. Because neighboring positions differ in one bit, a sensor read exactly on the boundary between two positions gives one of those two positions, an error of at most one step. With a binary pattern, a misaligned sensor could report a position on the other side of the disc.

ADC error reduction

Some analog-to-digital converter architectures produce Gray-coded intermediate results. When the input sits at the boundary between two output codes, only one bit is uncertain, so the error is limited to 1 LSB instead of a large jump in the converted value.

Status Counters Read Across Clock Domains

Network and storage controllers often keep event counters, such as packets received or errors detected, in a fast interface clock domain, while software reads them through a slower bus clock. Keeping the counter in Gray code, or passing a Gray copy across the boundary, lets the bus side capture a consistent value at any time without stopping the counter.

Timing Considerations

The two directions of conversion have very different timing costs:

  • Binary to Gray needs one layer of 2-input XOR gates, one per bit, all working in parallel. It is fast at any width.
  • Gray to binary needs each binary bit to be the XOR of the Gray bit and all Gray bits above it: b[i] = b[i+1] ^ g[i]. Written directly, this is a chain of N - 1 XOR gates in series, which can become a timing bottleneck for wide or high-frequency counters. Synthesis tools can restructure it into a tree, and the conversion can be pipelined if needed.

Asynchronous FIFOs avoid the expensive direction where possible by comparing the Gray pointers directly instead of converting them back to binary.

PPA Impact: A Gray counter toggles exactly one flip-flop per clock, while a binary counter toggles an average of almost two. For counters that run continuously, such as address generators, this reduces switching activity and therefore dynamic power.

Design

This design keeps a binary counter q and registers its Gray-coded value in out. Two equivalent ways of writing the conversion are shown, selected with an `ifdef: a loop over the bits, and a single concatenation.


module gray_ctr
  # (parameter N = 4)

  (	input 	clk,
	input 	rstn,
	output reg [N-1:0] out);

	reg [N-1:0] q;                     // Internal binary counter
	integer i;

	always @ (posedge clk) begin
		if (!rstn) begin
    	q <= 0;
    		out <= 0;
      end else begin
  		q <= q + 1;

`ifdef FOR_LOOP
    	// Gray bit i is the XOR of binary bits i+1 and i
    	for (i = 0; i < N-1; i= i+1) begin
      	out[i] <= q[i+1] ^ q[i];
    	end
    	out[N-1] <= q[N-1];             // The MSB is copied unchanged
`else
			// Same conversion in one line: {MSB, pairwise XOR of neighbors}
			out <= {q[N-1], q[N-1:1] ^ q[N-2:0]};
`endif
    end
	end
endmodule

Both versions compute q ^ (q >> 1). Note that out is calculated from the current value of q, before it increments, so out always holds the Gray code of the previous count. It lags the binary counter by one clock cycle.

Synthesis result: The tool builds an N-bit binary counter (flip-flops and an incrementer), N - 1 XOR gates, and N more flip-flops for out. Because out comes straight from flip-flops, it changes cleanly on the clock edge, one bit at a time. The XOR gates themselves can glitch while several bits of q change, but those glitches are filtered by the out register and never reach the output.

Low-Power Address Sequencing

Memory controllers and DSP blocks that step through buffers in order, such as for audio samples or image lines, spend power on every bit that toggles on the address bus. Generating the address sequence in Gray code toggles one address line per access instead of several, which saves dynamic power on long, heavily loaded address wires.

Testbench

The testbench uses a 20 ns clock period, holds reset for two clock edges, then runs for 20 edges, which covers the full 16-value sequence and part of the next.


module tb;
  parameter N = 4;

  reg clk;
  reg rstn;
  wire [N-1:0] out;

  // Pass N to the design so both use the same width
  gray_ctr #(.N(N)) u0 (	.clk(clk),
               .rstn(rstn),
               .out(out));

  always #10 clk = ~clk;        // Rising edges at 10, 30, 50, ...

  initial begin
    {clk, rstn} <= 0;

    $monitor ("T=%0t rstn=%0b out=0x%0h", $time, rstn, out);

    repeat(2) @ (posedge clk);
    rstn <= 1;
    repeat(20) @ (posedge clk);
    $finish;
  end
endmodule
Output
$ /usr/bin/vvp simulation +random_seed+279313274
T=0 rstn=0 out=0xx
T=10 rstn=0 out=0x0
T=30 rstn=1 out=0x0
T=70 rstn=1 out=0x1
T=90 rstn=1 out=0x3
T=110 rstn=1 out=0x2
T=130 rstn=1 out=0x6
T=150 rstn=1 out=0x7
T=170 rstn=1 out=0x5
T=190 rstn=1 out=0x4
T=210 rstn=1 out=0xc
T=230 rstn=1 out=0xd
T=250 rstn=1 out=0xf
T=270 rstn=1 out=0xe
T=290 rstn=1 out=0xa
T=310 rstn=1 out=0xb
T=330 rstn=1 out=0x9
T=350 rstn=1 out=0x8
T=370 rstn=1 out=0x0
T=390 rstn=1 out=0x1
T=410 rstn=1 out=0x3
testbench.v:22: $finish called at 430 (1ns)
T=430 rstn=1 out=0x2

The output follows the Gray column of the table above: 0, 1, 3, 2, 6, 7, 5, 4, c, d, f, e, a, b, 9, 8, then back to 0 at 370 ns. Converting consecutive values to binary shows that exactly one bit changes on every step, including the wrap from 8 (1000) to 0 (0000).

Quick Check

Q: Reset is released at 30 ns, and the rising edge at 50 ns increments q. Why does out not change until 70 ns?

Show Answer

At 50 ns, q changes from 0 to 1, but out is computed from the value q had before the edge, which was 0, so out stays 0. At 70 ns, out receives the Gray code of 1. The registered output lags the binary count by one clock cycle.

Common Beginner Mistakes

Mistake #1: Converting to Gray with combinational logic only

Wrong: assign gray = q ^ (q >> 1); sent straight to another clock domain
Right: Register the Gray value first, as out does in this design

Why? When several bits of q change on one edge, the XOR outputs can glitch through several values before settling. The one-bit-change guarantee holds only for a value that comes directly from flip-flops. A synchronizer in another domain that samples the unregistered XOR outputs can capture a glitch.

Mistake #2: Shifting in the wrong direction

Wrong: gray = q ^ (q << 1);
Right: gray = q ^ (q >> 1);

Why? Each Gray bit is the XOR of a binary bit with the bit above it, and the MSB is copied unchanged. A left shift XORs each bit with the bit below it instead, which produces a sequence where several bits change at once. Checking the first few values against the Gray table catches this quickly.

Mistake #3: Adding 1 to the Gray value

Wrong: out <= out + 1; where out holds a Gray code
Right: Increment a binary counter and convert it, or convert the Gray value to binary, add 1 and convert back

Why? Addition works on binary numbers. Adding 1 to a Gray value produces the binary successor of that bit pattern, not the next Gray code. From 0011 (count 2), + 1 gives 0100 (count 7) instead of 0010 (count 3).

Mistake #4: Using a Gray counter with a modulus that is not a power of two

Wrong: Converting a Mod-10 binary counter to Gray and expecting one-bit changes everywhere
Right: Use a power-of-two length, or a special Gray sequence designed for that modulus

Why? The single-bit change at the wrap-around holds only for the full 2N sequence. A Mod-10 counter wraps from 9 (Gray 1101) to 0 (Gray 0000), which changes three bits at once. In an asynchronous FIFO, this is why depths are normally powers of two.

Practice Exercise

Challenge: Gray to Binary Converter

Write a combinational, parameterized module gray2bin with an N-bit Gray input g and an N-bit binary output b. Use a for loop. Then work out, for N = 4, which Gray input gives b = 4'd10.

Hint

The MSB is copied: b[N-1] = g[N-1]. Each lower bit is the XOR of the Gray bit with the binary bit just above it: b[i] = b[i+1] ^ g[i]. Work from the MSB downward, using blocking assignments so each iteration sees the bit computed before it.

Solution

module gray2bin #(parameter N = 4) (
  input      [N-1:0] g,
  output reg [N-1:0] b
);

  integer i;

  always @(*) begin
    b[N-1] = g[N-1];                   // MSB is the same in both codes
    for (i = N-2; i >= 0; i = i - 1)
      b[i] = b[i+1] ^ g[i];            // Each bit depends on the bit above it
  end

endmodule

Binary 10 is 1010, and its Gray code is 1010 ^ 0101 = 1111, so g = 4'hf gives b = 4'd10, which matches the log, where 0xf appears as the 10th value after 0. The loop unrolls into a chain of N - 1 XOR gates, because each bit needs the one above it, which is the timing cost described in the Timing Considerations section.

Hands-On Drills

Write and run these in ChipVerify Lab. Each drill is graded, and when your code fails, the grader explains which mistake it found.

Gray-Code Counter

Count in binary and output the Gray code.

Medium, 18 minPRO

Summary

In this tutorial, you learned:

  • A Gray counter visits all 2N states, changing exactly one bit per clock, including at the wrap-around
  • Binary to Gray conversion is g = b ^ (b >> 1), one XOR gate per bit
  • A single changing bit means a sampled value is always either the old or the new count
  • Asynchronous FIFOs pass Gray-coded pointers between clock domains for this reason
  • The Gray output must come directly from flip-flops; unregistered XOR outputs can glitch
  • Gray to binary conversion is a chain of XOR gates and can limit timing in wide counters
  • The one-bit property only holds for power-of-two sequence lengths
Did you find what you were looking for?

Quiz

Test Your Knowledge

1 of 5 Score: 0 / 5
Cron Job Starts