Gray Code Counter

A 3-bit counter whose output steps through the Gray code sequence 000→001→011→010→110→111→101→100→000… advancing when en is high. Synchronous reset to 000.

Port Dir Width Meaning
clk, rst, en in 1 clock, sync reset, enable
q out 3 Gray-coded count

Hint: keep a binary counter internally and output bin ^ (bin >> 1) — or update the Gray value directly if you're feeling brave. Refresher: the Gray code tool.

Show the testbench (the grader)
tb.v — locked
`timescale 1ns/1ps
module tb;
    reg clk=0, rst=1, en=0; wire [2:0] q;
    reg [2:0] bin = 0; reg [2:0] want;
    integer i, errors=0; reg [31:0] lfsr = 32'h1234;
    challenge dut (.clk(clk), .rst(rst), .en(en), .q(q));
    always #5 clk = ~clk;
    initial begin
        $dumpfile("wave.vcd"); $dumpvars(0, tb);
        repeat (2) @(negedge clk); rst = 0;
        for (i = 0; i < 200; i = i + 1) begin
            @(negedge clk);
            lfsr = {lfsr[30:0], lfsr[31]^lfsr[21]^lfsr[1]^lfsr[0]};
            en = lfsr[2];
            @(posedge clk);
            if (en) bin = bin + 3'd1;
            want = bin ^ (bin >> 1);
            #1;
            if (q !== want) begin
                errors = errors + 1;
                if (errors < 6)
                    $display("FAIL @%0t: q=%b want=%b", $time, q, want);
            end
        end
        if (errors == 0) $display("TB PASS");
        else $display("TB FAIL (%0d errors)", errors);
        $finish;
    end
endmodule