HDLbits
Start Practicing

Verification/Writing Testbenches

Verify an FSM's Output Sequence

medium
writing-testbenchesself-checkingfsmsequential

The DUT below is a Moore-machine finite state machine that watches a serial bit stream on in and asserts detected for one cycle every time the most recent three bits received were 1, 0, 1 — including overlapping matches (e.g. the stream 1,0,1,1,0,1 contains two overlapping occurrences of 101, sharing the middle 1,0,1… check the trace below for a worked example).

The DUT (given, fixed)

module seq_detector (
    input  clk,
    input  reset,
    input  in,
    output detected
);

    localparam S0 = 2'd0, S1 = 2'd1, S10 = 2'd2, S101 = 2'd3;
    reg [1:0] state, next_state;

    always @(posedge clk) begin
        if (reset)
            state <= S0;
        else
            state <= next_state;
    end

    always @(*) begin
        case (state)
            S0:      next_state = in ? S1   : S0;
            S1:      next_state = in ? S1   : S10;
            S10:     next_state = in ? S101 : S0;
            S101:    next_state = in ? S1   : S10;
            default: next_state = S0;
        endcase
    end

    assign detected = (state == S101);

endmodule

reset is synchronous and active-high. detected is a Moore output: it depends only on the current state, and becomes 1 the cycle immediately after the third bit of a 101 pattern is clocked in.

Your task

Complete the testbench so that it:

  1. Resets the FSM and confirms detected starts low.
  2. Feeds the bit stream 1, 0, 1, 0, 1, 1, 0, 1 into in, one bit per rising edge of clk.
  3. After each edge, checks detected against the expected sequence 0, 0, 1, 0, 1, 0, 0, 1.
  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
in input 1 Serial bit stream, one bit sampled per rising edge
detected output 1 High for one cycle whenever the last 3 bits clocked in were 1,0,1

Notes

  • Work through the state transitions by hand first (or trust the table above) so you know exactly which cycles should show detected = 1 before you write the checks.
  • Bits 3, 5, and 8 of the stream each complete a 101 pattern; note that bit 5 reuses bit 4’s trailing 0 and bit 3’s trailing 1, which is exactly the “overlapping match” behavior this FSM supports.