Difficulty: Easy · Puzzle 4 of 6 · Topic: Reset Puzzles
The counter is reset correctly at start-up (rst_n=0, en=0). Later rst_n is asserted at t=47 while en is still 1. What do the two prints show, and what should they show? Fix the code.
`timescale 1ns/1ns
module tb;
reg clk = 0, rst_n = 0, en = 0;
reg [3:0] cnt;
always #5 clk = ~clk; // posedges at 5, 15, 25, ...
always @(posedge clk) begin
if (en) cnt <= cnt + 1;
else if (!rst_n) cnt <= 4'd0;
end
initial begin
#17 rst_n = 1; en = 1; // normal operation: counts at 25, 35, 45
#30 rst_n = 0; // t=47: reset asserted while en is still 1
#9 $display("t=%0d cnt=%0d", $time, cnt); // after the edge at 55
#10 $display("t=%0d cnt=%0d", $time, cnt); // after the edge at 65
#1 $finish;
end
endmoduleRead the if / else if order from the top.
1) Start-up works only because en=0 at that time: the else-if branch is reached and the counter clears at edges 5 and 15.
2) From t=17 en=1: the counter counts at 25, 35, 45 and reaches 3.
3) At t=47 rst_n goes low but en is still 1, so the first branch wins every time and the else-if (reset) branch is never evaluated.
4) The counter keeps counting: 4 after the edge at 55, 5 after the edge at 65.
5) Fix: test reset first: if (!rst_n) cnt <= 0; else if (en) cnt <= cnt + 1; then both prints show 0.Answer: It prints cnt=4 at t=56 and cnt=5 at t=66; the counter ignores the reset because the enable branch has priority. It should print 0 and 0, which needs the reset test first in the if chain.
Checked by running the code in Icarus Verilog 13; the printed output supports the answer above. Icarus: the counter keeps counting while rst_n is low because the enable branch is tested first.
Believing the testbench's start-up reset proves the reset logic. It passed only because en happened to be 0 then. Reset must be the outermost, highest-priority condition of a synchronous process; test it with reset asserted while every enable and valid is active.
Which stimulus would have caught this at the start of the project? Model answer: asserting reset in the middle of activity (every enable and valid high) and checking that all state returns to its reset value, which a random reset-injection test or a mid-test reset sequence does automatically.