A counter is a register with next-value rules for increment, decrement, reload, and wrap. Terminal-count decode turns those counts into ticks, done flags, and timeouts.
6 lessons, about 32 min
16 states. The period is 2⁴ = 16 clock cycles, set by the register width; a modulo-M counter shortens it to M by resetting at M−1.
The whole topic on one page, taken from each lesson's Remember box. Read it before an interview, or print it.
Counting as Controlled State Evolution
An N-bit free-running counter has a period of 2^N cycles.
A modulo-M counter wraps after M-1, and tc is high while count holds M-1.
Decode tc with >=, not ==, so an out-of-range value cannot lock the counter. Guard the width for M = 1.
Up/Down Counter with Reload
Priority is reset, then load, then enabled counting.
Wrap suits addresses and pointers; saturate suits levels, credits and gain values.
Test it against a plain-integer reference model with random stimulus to find limit and priority bugs.
A Prescaler Feeding a Timer Tick
Slow logic acts only when tick is high, all on the same clock.
A tick is produced after one edge and consumed at the next, because both blocks read old values.
start wins over a coincident tick; the elapsed time to expiry depends on the start phase.
Rule of thumb: prefer a tick enable to a divided clock unless a real clock output is needed.
Watchdog Timer Example
A kick or a disable clears the counter; TIMEOUT kick-free cycles set a sticky timeout.
Only reset clears a fired timeout.
A safety-related watchdog needs its own low-frequency clock source.
A Gray-Code Counter
Binary to Gray is g = b XOR (b >> 1). Gray to binary is a prefix XOR from the top bit down.
Register the Gray value: convert the next binary count before the flop, and send only flop outputs across a crossing.
Only an even modulus can stay one-bit at the wrap, and only when it uses the codes centred in the cycle; an odd modulus never can.
Rule of thumb: a Gray count is safe to cross only if it comes straight from flops and moves by exactly one step at a time.
Mini Project: a Programmable Timer
A period is (psc + 1) x (top + 1) cycles; compare with >= so a smaller limit written mid-count ends the period at once.
Match on the step that lands on cmp, not on count == cmp, or the flag sets again while the count waits.
A sticky flag's set must beat its clear, or a match in the clearing cycle is lost.
Rule of thumb: for every flag, write down what happens when set and clear arrive in the same cycle, then test exactly that cycle.
Code lab: Enable counter
Practice question: Parameterised up/down counter with wrap or saturate
Code lab: Up/down counter
Practice question: Gray code counter for a CDC-friendly FIFO pointer
Practice question: FSM Gray encoding for low power and CDC safety
Interview: run a mock interview on this topic