HDLbits
Start Practicing

Verification/Writing Testbenches

Verify a Shift Register

medium
writing-testbenchesself-checkingshift-registersequential

The DUT below is a 4-bit serial-in, parallel-out shift register. Your job is to write a testbench that shifts in a known bit pattern and checks the register’s contents after every single shift, not just at the end.

The DUT (given, fixed)

module shift_reg4 (
    input        clk,
    input        reset,
    input        sin,
    output [3:0] q
);

    reg [3:0] q_r;
    assign q = q_r;

    always @(posedge clk) begin
        if (reset)
            q_r <= 4'b0000;
        else
            q_r <= {q_r[2:0], sin};
    end

endmodule

On every rising edge (when not resetting), the register shifts its contents one position toward q[3] and loads the new serial bit sin into q[0]. reset is synchronous and active-high.

Your task

Complete the testbench so that it:

  1. Resets the register and confirms q becomes 4'b0000.
  2. Shifts the bits 1, 0, 1, 1 into sin, one bit per rising edge.
  3. After each edge, checks q against the expected running contents: 4'b0001, 4'b0010, 4'b0101, 4'b1011.
  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
sin input 1 Serial data in, loaded into q[0] each shift
q output 4 Parallel register contents

Notes

  • Checking after every shift (not only the final value) is what makes this a strong testbench: a register that shifts in the wrong direction, or loads at the wrong bit position, would still happen to produce a correct-looking final value for some input patterns but would fail an intermediate check.
  • Trace it by hand: after shifting in 1, q = 0001; after 0, the old 1 moves to q[1] and a new 0 enters q[0], giving q = 0010; and so on.