Gray Code Counter with Synchronous Reset
Asynchronous FIFOs rely on Gray code counters for their read and write pointers to safely pass state across clock domains. If a Gray pointer initializes to an unknown state or glitches upon reset, the FIFO will immediately calculate incorrect empty or full flags and corrupt data.
This module maintains an internal 4-bit binary counter and outputs the corresponding 4-bit Gray code. The counter increments by one whenever the enable signal is asserted. To guarantee glitch-free outputs for clock domain crossing, the Gray code output must be strictly registered.
The circuit operates on the positive edge of the clock. It uses a synchronous, active-high reset. When reset is asserted, both the internal binary state and the registered Gray output must immediately go to zero on the next clock edge. If reset and enable are asserted simultaneously, reset takes priority.
Worked Trace: Cycle 1: rst=1, en=0 → bin=0, gray_out=0 Cycle 2: rst=0, en=1 → bin=1, gray_out=1 Cycle 3: rst=0, en=1 → bin=2, gray_out=3 Cycle 4: rst=0, en=0 → bin=2, gray_out=3 (hold) Cycle 5: rst=0, en=1 → bin=3, gray_out=2 Cycle 6: rst=0, en=1 → bin=4, gray_out=6
{ "signal": [
{ "name": "clk", "wave": "p......" },
{ "name": "rst", "wave": "10....." },
{ "name": "en", "wave": "011011." },
{},
{ "name": "gray_out", "wave": "======.", "data": ["0", "1", "3", "3", "2", "6"] }
], "head": { "text": "Synchronous reset and count behavior." } }| Signal | Direction | Width | Description | |--------|-----------|-------|-------------| | clk | input | 1 | Positive-edge triggered clock | | rst | input | 1 | Synchronous active-high reset; forces internal binary and gray_out to 0 | | en | input | 1 | Enable; counter increments on posedge clk while en=1 | | gray_out | output | 4 | Registered Gray code output |
Constraints
- The
gray_outport must be driven directly by a flip-flop; combinational logic on the output is strictly prohibited. - Both the internal binary counter and the output register must reset synchronously to
clk. - The reset signal
rstis active-high. - If
rstandenare asserted on the same clock cycle,rsttakes priority. - The 4-bit counter must naturally wrap from 15 (4'b1111) back to 0 (4'b0000) when incremented.
Topics
Solve this problem
Write the module in Verilog, SystemVerilog or VHDL. Your submission is compiled and simulated against a real testbench — you get the waveform back, not a stored answer.
This problem is part of Codiode Pro. The statement above is free to read.
The circuit builder and code editor need a desktop screen. On a phone, read the problem here and open it on a laptop to solve.