Wrapping counter
Increment on the specified event and return to zero on the next event at the limit. Verify the 5-to-0 transition of a modulo-6 counter and add idle cycles near the limit to check that the count holds.
A scanner advances one position per accepted work event. It has positions 0 through 5. An idle edge at position 5 must leave it there. The next work event takes it back to 0.
Modulo 6 wraps on the next event
Three bits can represent all six positions, plus 6 and 7. Natural three-bit overflow occurs after 7. A modulo-6 counter needs an explicit rule to take an event at 5 back to 0. An idle edge holds the count.
Use the event to choose increment or wrap
Synchronous reset clears count and wrapped. Each rising edge records in wrapped whether that edge took 5 to 0. The next sample recomputes the flag.
module wrapping_counter (
input logic clk,
input logic rst_n,
input logic event_i,
output logic [2:0] count,
output logic wrapped
);
always_ff @(posedge clk) begin
if (!rst_n) begin
count <= 3'd0;
wrapped <= 1'b0;
end else begin
wrapped <= event_i && (count == 3'd5);
if (event_i)
count <= (count == 3'd5) ? 3'd0 : count + 3'd1;
end
end
endmodule
Hold 5 on an idle edge, then wrap
E0 resets the counter. The work-event sequence for E1 through E9 is 111110110. E1 through E4 advance count to 4. The table starts at E5 and shows the post-update values.
| Edge | event_i | Count | wrapped |
|---|---|---|---|
| E5 | 1 | 5 | 0 |
| E6 | 0 | 5 | 0 |
| E7 | 1 | 0 | 1 |
| E8 | 1 | 1 | 0 |
| E9 | 0 | 1 | 0 |
event_i marks work at the rising edge. Each high sample is one event, so consecutive high samples increment on consecutive edges. If the count should stop at its limit, compare the saturating counter under the same event sequence.
Replay the lab
Extract the executable lab on Linux or WSL and run bash run.sh. Icarus Verilog 12.0 checked 10 timed observations. The archive contains the RTL, testbench, log, VCD and generic Yosys structure. The checks include the idle edge at the limit, the wrap and the first increment after wrap. Continue with F09 on counters, F12 on self-checking tests.
Interactive lab
Reset, then apply five event edges to reach 5. Sample one idle edge, then apply the sixth event.
- Count
- Wrap pulse wrapped
Show the last eight observations
Teaching film
Run the RTL yourself
Extract the lab and follow the commands in its README. Compare the simulated outputs and waveform with your predictions from the interactive lab.
Download Wrapping counter RTL (.zip)