// Self-checking testbench for the three 1011 detectors. // A shift register of the last four input bits is the reference model. // Run with Icarus: iverilog -g2012 -o sim tb_seq_detect.sv seq_detect_moore.sv \ // seq_detect_mealy.sv seq_detect_1p.sv && vvp sim `timescale 1ns / 1ps module tb_seq_detect; logic clk; logic rst = 1'b1; logic din = 1'b0; logic det_moore, det_mealy, det_1p; seq_detect_moore u_moore (.clk(clk), .rst(rst), .din(din), .detect(det_moore)); seq_detect_mealy u_mealy (.clk(clk), .rst(rst), .din(din), .detect(det_mealy)); seq_detect_1p u_1p (.clk(clk), .rst(rst), .din(din), .detect(det_1p)); initial begin // 100 MHz clock clk = 1'b0; forever #5 clk = ~clk; end // Reference model: the last four bits that were clocked in. logic [3:0] hist; always_ff @(posedge clk) begin if (rst) hist <= 4'b0000; else hist <= {hist[2:0], din}; end int errors; int n_match; // Checker: compare every DUT output with the model in the middle of // each cycle, when all signals are stable. initial begin errors = 0; n_match = 0; forever begin @(negedge clk); if (rst) continue; // Moore outputs reflect the bits already clocked in. if (det_moore !== (hist == 4'b1011)) begin $error("Moore: hist=%b detect=%b", hist, det_moore); errors++; end if (det_1p !== (hist == 4'b1011)) begin $error("1-process: hist=%b detect=%b", hist, det_1p); errors++; end // Mealy output also sees the bit on din right now. if (det_mealy !== ({hist[2:0], din} == 4'b1011)) begin $error("Mealy: hist=%b din=%b detect=%b", hist, din, det_mealy); errors++; end if (hist == 4'b1011) n_match++; end end // Drive one bit per clock, changing din just after the rising edge. task automatic send_bits(input logic [31:0] bits, input int n); for (int i = n - 1; i >= 0; i--) begin @(posedge clk); din <= bits[i]; end endtask integer seed = 8; // fixed seed: repeatable run initial begin repeat (3) @(posedge clk); rst <= 1'b0; // Directed cases: a plain match, an overlapping match, near misses. send_bits(32'b1011, 4); send_bits(32'b1011011, 7); // 1011 then 011 -> two matches send_bits(32'b1001_1010_1111, 12); // Random cases repeat (2000) begin @(posedge clk); din <= 1'($random(seed)); end @(posedge clk); @(posedge clk); if (errors == 0) $display("PASS: %0d matches seen, 0 errors", n_match); else $display("FAIL: %0d errors", errors); $finish; end endmodule