fpga4fun.comwhere FPGAs are fun

Counters 3 - Gray counters

A Gray counter is a binary counter where only one bit changes at a time.
Here's how a 4bit Gray counter goes.

0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
and then wraps back to 0000...

To create a Gray counter, first make a binary counter and then convert the value to Gray.

module GrayCounter(
  input clk,
  output [3:0] cnt_gray
);

reg [3:0] cnt = 0;
always @(posedge clk) cnt <= cnt+1;  // 4bit binary counter

assign cnt_gray = cnt ^ (cnt >> 1);  // then convert to gray
endmodule

More generally, use these modules to convert to and from Gray code.

module bin2gray #(parameter W=4) (
	input [W-1:0] bin,
	output [W-1:0] gray
);
assign gray = bin ^ (bin >> 1);
endmodule

module gray2bin #(parameter W=4) (
	input [W-1:0] gray,
	output [W-1:0] bin
);
assign bin = gray ^ (bin >> 1);
endmodule

Gray code is particularly useful to send values across clock domains (this way it has an uncertainty of only 1).

More info on Wikipedia.