Difficulty: Medium · Puzzle 5 of 6 · Topic: Digital Logic Puzzles
Analyze this RTL and state the sequence and period of q. Also identify one synthesis-safe improvement.
always_ff @(posedge clk or negedge rst_n) begin
if (!rst_n) q <= 3'd0;
else if (q == 3'd5) q <= 3'd0;
else q <= q + 3'd1;
endTrace q values cycle by cycle from reset.
1) Starting from reset q=0.
2) On each clock: 0,1,2,3,4,5 then wrap to 0.
3) So modulus (period in states) is 6.
4) Values 6 and 7 are unreachable in normal operation.
5) Improvement: add explicit recovery for illegal states (q>5) to 0 for robustness after X-corruption or partial reset.Answer: q cycles 0->1->2->3->4->5->0 with period 6; add illegal-state recovery for safety.
Calling it a 3-bit free-running counter (mod-8) without reading the compare branch.
How would you implement a glitch-free terminal-count pulse for q==5?