HDLbits
Start Practicing

Verification/Writing Testbenches

Verify a Counter's Sequence

medium
writing-testbenchesself-checkingcounterssequential

The DUT below is a simple 4-bit up counter. Your job is to write a testbench that clocks it for long enough to prove it counts correctly, including wrapping around from its maximum value back to zero.

The DUT (given, fixed)

module counter4 (
    input        clk,
    input        reset,
    output [3:0] count
);

    reg [3:0] count_r;
    assign count = count_r;

    always @(posedge clk) begin
        if (reset)
            count_r <= 4'b0000;
        else
            count_r <= count_r + 4'b0001;
    end

endmodule

count starts wherever it wants after power-up, but a synchronous, active-high reset forces it to 4'b0000 on the next rising edge. From then on, it increments by one on every rising edge of clk, wrapping from 4'b1111 back to 4'b0000.

Your task

Complete the testbench so that it:

  1. Applies reset for one clock edge and confirms count becomes 0.
  2. Releases reset and pulses the clock at least 20 more times.
  3. After every edge, checks that count equals the previous value plus one (accounting for wraparound at 4'b1111 -> 4'b0000).
  4. Tracks errors and reports SIMULATION PASSED / SIMULATION FAILED (%0d errors) at the end.

Interface (of the DUT under test)

Signal Direction Width Description
clk input 1 Clock, rising-edge triggered
reset input 1 Synchronous, active-high
count output 4 Increments by 1 every rising edge unless reset is high

Notes

  • Keep your own expected register in the testbench and increment it in lockstep with the DUT; a 4-bit expected register will wrap on overflow exactly like the DUT’s count, so you don’t need a special case for the 1111 -> 0000 transition.
  • Running for at least 17 edges after reset guarantees you exercise the wraparound at least once (16 counts to get from 0000 back to 0000); 20 gives a comfortable margin.