Write the contract
The counter updates on the rising clock edge. Reset is active high and synchronous: it takes effect on that edge, not when the reset signal changes. Reset has priority over enable. With reset low and enable low, the count holds. An enabled count of 15 wraps to 0.
| Reset | Enable | Next count |
|---|---|---|
| 1 | Either | 0 |
| 0 | 0 | Current count |
| 0 | 1 | (Current count + 1) modulo 16 |
Implement the state update
Nonblocking assignments describe the registered update. There is no assignment in the hold case, so the register retains its value.
module counter (
input logic clk, reset, enable,
output logic [3:0] count
);
always_ff @(posedge clk) begin
if (reset) count <= 4'd0;
else if (enable) count <= count + 4'd1;
end
endmoduleCheck every state/control combination
The testbench resets the design, reaches a chosen starting state, applies one of four reset/enable combinations, and compares the result with the contract. That gives 16 × 2 × 2 = 64 checked transitions.
Inputs change at the falling edge, away from the sampling edge. The check runs one nanosecond after the next rising edge so the scheduled register update completes. A failed setup or transition stops the simulation with a nonzero result.
Read the complete testbench
module tb;
timeunit 1ns; timeprecision 1ps;
logic clk=0, reset=0, enable=0;
logic [3:0] count; int checks=0;
counter dut(.*); always #5 clk=~clk;
task automatic step(input bit r,input bit e);
@(negedge clk); reset=r; enable=e;
@(posedge clk); #1;
endtask
initial begin
for(int state=0;state<16;state++) for(int r=0;r<2;r++) for(int e=0;e<2;e++) begin
step(1,0); repeat(state) step(0,1);
if(int'(count)!=state) $fatal(1,"State setup failed");
step(1'(r),1'(e));
if(int'(count)!=((r!=0)?0:((e!=0)?(state+1)%16:state))) $fatal(1,"Transition failed");
checks++;
end
$display("PASS: %0d state/control transitions",checks); $finish;
end
endmoduleRun and inspect the result
Place both files in a folder without spaces. With Verilator and a supported C++ build toolchain installed, run:
verilator --binary --timing --top-module tb -Wno-TIMESCALEMOD --Mdir build counter.sv tb.sv
./build/VtbThe example was run with Verilator 5.046. The warning option covers the untimed counter alongside the timed testbench; it does not disable functional checks. Investigate other warnings.
Make the test earn your confidence
Change the counter to add two instead of one. The test should fail. Restore it, then change reset priority and confirm that reset-plus-enable catches it. Keep correct and modified versions separate so a failing example never replaces the working reference.