Part of Curriculum: Memory and FIFO Design (Module 1: Sequential Logic)
View Full Roadmap →
Level 4 Hard ★ Flagship #35 50 pts ✓ Solved

Gray Code Counter — Gray Encoding

Sequential Logic · cdc, industry-rtl, arbiters, clock-domain-crossing, hard, gray-codes

Implement a 4-bit Gray code counter that advances by exactly one bit per transition: 0000, 0001, 0011, 0010, 0110, 0111, 0101, 0100...

Write a synthesizable Verilog module named top_module matching the ports below exactly.
📐 Circuit Schematic Diagram
ingray[3:0]>clkrst_nGRAY CODE COUNTERSEQUENTIAL COUNTER
⚡ Timing & Synthesizability Constraints

Timing Contract: Transitions on `posedge clk`. Hamming distance between consecutive output words is strictly 1.

RTL Constraints: 4-bit output vector `gray[3:0]`. Modulo-16 cyclic sequence.

Objective: Understand Gray code arithmetic, binary-to-Gray conversion ($G = B \oplus (B >> 1)$), and glitch-free multi-bit CDC.

Prerequisites: Binary counters, XOR logic, CDC pointer synchronization.
NameDirWidthDescription
clkinput1Clock signal
areset_ninput1Active-low asynchronous reset
grayoutput44-bit Gray code count value
Expected Waveform (Golden Timing Contract)
💡 Need Guidance? Progressive Hints (3 Levels)
Hint 1: Conceptual Direction & Hardware Primitives
Maintain an internal binary counter `bin_cnt`.
Hint 2: Implementation Architecture & Approach
Convert next binary value to Gray code using the canonical formula: `gray <= next_bin ^ (next_bin >> 1);`.
Hint 3: Edge Cases, Timing & Verilog Syntax
Register the Gray output to eliminate combinational glitch transitions.
🔒 Reveal Verified Reference RTL Solution (Click to expand)
⚠️ Self-Discovery Warning: Try solving and simulating first! Viewing the verified reference implementation will bypass the real debugging experience.
Verified Synthesizable RTL
module top_module(
  input        clk,
  input        areset_n,
  output reg [3:0] gray
);
  reg [3:0] bin_cnt;

  always @(posedge clk or negedge areset_n) begin
    if (!areset_n) begin
      bin_cnt <= 4'b0000;
      gray    <= 4'b0000;
    end else begin
      bin_cnt <= bin_cnt + 1'b1;
      gray    <= (bin_cnt + 1'b1) ^ ((bin_cnt + 1'b1) >> 1);
    end
  end
endmodule
Verilog-2001 / SV Saved
Font: |
// Click Run Tests (or press Ctrl+Enter) to compile your RTL and simulate against hidden testbenches.
Simulation Timing Diagram (VCD Waveform)
100%
No simulation waveform yet. Run tests to simulate and generate VCD traces.
No compilation run yet. Syntax warnings and elaboration messages will appear here.
No simulation output yet. Raw stdout from vvp will appear here.

RTL Problems / Level 4 · Sequential Logic

What You Will Learn

By solving Gray Code Counter — Gray Encoding, you will acquire core industry skills:

  • Synthesizable hardware modeling in standard Verilog-2001 / SystemVerilog.
  • Correct handling of interface port contracts, edge-triggered clocks, and active-low/high resets.
  • Simulation waveform interpretation and debugging using timing diagrams (VCD traces).
  • Architectural avoidance of timing violations, glitching hazards, and synthesis warnings.

Problem Statement & Requirements

Implement a 4-bit Gray code counter that advances by exactly one bit per transition: 0000, 0001, 0011, 0010, 0110, 0111, 0101, 0100...

Hardware design teams at leading semiconductor firms evaluate these exact port contracts, race-condition assertions, and corner cases during technical design reviews and ASIC engineer interviews.

Objective: Understand Gray code arithmetic, binary-to-Gray conversion ($G = B \oplus (B >> 1)$), and glitch-free multi-bit CDC.

Prerequisites: Binary counters, XOR logic, CDC pointer synchronization.

Port List & Interface Timing

The hidden testbench instantiates top_module. Module port names and bit-widths must match the interface contract exactly:

NameDirWidthDescription
clkinput1Clock signal
areset_ninput1Active-low asynchronous reset
grayoutput44-bit Gray code count value

Timing Constraints & Synthesizable RTL Rules

⚡ Synthesizable Implementation Guidelines

Timing Contract: Transitions on `posedge clk`. Hamming distance between consecutive output words is strictly 1.

Synthesis Constraints: 4-bit output vector `gray[3:0]`. Modulo-16 cyclic sequence.

Architectural Deep Dive & Implementation Walkthrough

Standard binary counters change multiple bits simultaneously (e.g. $0111 \to 1000$ flips all 4 bits). In a CDC crossing, routing skew would cause the destination clock to sample intermediate false values ($0110, 0000, 1111$). A Gray code guarantees that exactly ONE bit changes between any two consecutive values, making multi-bit CDC safe.

Common RTL Designer Pitfalls

⚠️ Common Mistakes to Avoid

['Converting to Gray code through unclocked combinational gates before crossing domains: logic glitches defeat the purpose of Gray coding.', 'Using non-power-of-2 modulo counts with Gray code without folding: rolling over from an arbitrary count back to 0 breaks the 1-bit Hamming distance guarantee.']

Silicon & Hardware Engineering Notes

🛠️ ASIC vs FPGA Hardware Considerations

Gray coding is mandatory for all asynchronous FIFO read/write pointer synchronizers across chips, networking ASICs, and GPUs.

Starter RTL Code

module top_module(
  input        clk,
  input        areset_n,
  output reg [3:0] gray
);

  // 4-bit Gray code counter

endmodule

Verified Reference Solution

🔒 Reveal Verified Reference RTL Solution
module top_module(
  input        clk,
  input        areset_n,
  output reg [3:0] gray
);
  reg [3:0] bin_cnt;

  always @(posedge clk or negedge areset_n) begin
    if (!areset_n) begin
      bin_cnt <= 4'b0000;
      gray    <= 4'b0000;
    end else begin
      bin_cnt <= bin_cnt + 1'b1;
      gray    <= (bin_cnt + 1'b1) ^ ((bin_cnt + 1'b1) >> 1);
    end
  end
endmodule
Advertisement

Related RTL Problems in Level 4

Frequently Asked Questions

What does Gray Code Counter — Gray Encoding require?

Implement a 4-bit Gray code counter that advances by exactly one bit per transition: 0000, 0001, 0011, 0010, 0110, 0111, 0101, 0100... Implement it as Verilog module top_module matching the listed ports.

Is this design combinational or sequential?

Tags: cdc, industry-rtl, arbiters, clock-domain-crossing, hard, gray-codes. If a clock signal is present in the port table, implement it as sequential logic; otherwise, use continuous assignments or combinational blocks.

How is my solution graded?

A hidden SystemVerilog testbench simulates your module in the cloud judge. You pass when all directed corner cases match the golden model and the VCD timing waveform matches the contract.

How does this challenge help with semiconductor interviews?

Technical interviewers at NVIDIA, Qualcomm, Apple, and Intel routinely ask candidates to code, debug, and explain the timing waveforms of Gray Code Counter — Gray Encoding to assess real-world synthesizability and race-condition awareness.

Advertisement