RTL Design #15 · 2026-10-08 · Gray code · Easy · about 10 min
A Gray counter that changes two bits
gray_counter is a W-bit counter whose output is in Gray code, so it can be sampled safely from another clock domain.
- After reset,
grayis 0. - At each rising edge with
en = 1it moves to the Gray code of the next count: when the count isn,grayisn ^ (n >> 1). The count wraps from 2W − 1 to 0. - With
en = 0it holds.
So exactly one bit of gray changes at every step, including the wrap. The module must work for any W.
The current design starts well, 0000, 0001, 0011, 0010, 0110, and then goes wrong. Fix gray_counter.sv.
Write and run your answer in the browser. The hidden tests check it, and it’s free.