29 / 63 · Concept
State count, counter width and unused codes
Derive storage width from the count range and define recovery from invalid states.
Lessons are free to read. Enroll to save your learning progress.
A counting circuit is a state machine too
A counter cycling from 0 through 9 needs ten states, hence at least storage bits. A four-bit registerRegister A circuit that stores multiple bits of state. The synchronous registers in this course store their specified inputs at a clock edge. Learn more has 16 patterns, however, so choosing the correct width alone does not implement modulo-10 behavior.
M is the number of states, not the maximum value. Counting 0 through M-1 differs from counting 0 through M. If parameter M=1 is supported, limit the storage width to at least one bit and keep its value at 0.
Four-bit storage has 16 codes, but modulo-10 uses only ten as normal states. After choosing width, add comparison and recovery policies.
- 10 states: Valid count is 0–9
- Four-bit storage: 16 codes; 10–15 are unused
- Next state: 0 if en=1 and count≥9
Out-of-range states are part of the design
What happens if a four-bit modulo-10 counter somehow reaches 12? Either establish initialization/resetReset A control that returns state to a specified initial value. Define whether it is synchronous or asynchronous and whether it has priority over other controls. Learn more conditions that justify assuming it cannot happen, or define recovery to 0 for states 9 and above. Recovery logic does not guarantee tolerance of every hardware fault.
always_ff @(posedge clk) begin
if (rst) count <= 4'd0;
else if (en) begin
if (count >= 4'd9) count <= 4'd0;
else count <= count + 4'd1;
end
endThis example also recovers invalid values 10–15 at an edge with en=1. With enable=0 it retains even those values. A specification requiring immediate recovery needs different condition priority.
Width review and functional review are separate
Ten bits can represent 0–999, but unconstrained incrementing reaches 1023. Comparison and selection logic must return to 0 at the specified maximum state. In memory-address, iteration-count and packet-length counters, this distinction can cause invalid accesses or length errors.
Try it yourself
Find the minimum width and number of unused codes for a counter cycling through 0–99. What changes if you simply add 1 at that width?
Read the explanation
One hundred states require seven bits, leaving unused codes. A simple incrementer continues beyond 99 to 127, so it is modulo-128 rather than modulo-100.