Digital Systems 3 min read

Registers and counters

Put flip-flops side by side with a shared clock and you have a register. Connect them in a chain and the bits shift along, as in SPI. Make each one toggle and the chain counts, which is the core of every timer.

Four D flip-flops in a row share one clock. The serial input feeds the first flip-flop and each output feeds the next. On every clock edge the bits move one place along. After four edges, the input bits 1, 0, 1, 1, first bit first, sit in the four flip-flops as 1, 1, 0, 1 from first to last; read from last to first, that is 1011.
A 4-bit shift register moves the bits one place on every clock edge.

Register: flip-flops with one clock

An 8-bit register is eight D flip-flops sharing a clock. On each edge all eight copy their inputs at once, so a whole byte is stored together. Peripheral and CPU registers work this way, usually with an enable that tells them when to load a new value.

Shift register: one bit at a time

Connect each flip-flop's output Q to the next one's input D, and on every clock edge the pattern moves one place along, with a new bit entering at the front. Four edges push a 4-bit value in serially, and the four outputs then hold it in parallel. This is how SPI sends a byte over one wire, and how a cheap serial-in, parallel-out chip such as the 74HC595 gives you extra output pins from three.

Try it with the input bits 1, 0, 1, 1, first bit first. After four edges the first bit has travelled all the way to the last flip-flop, and reading the outputs from the last back to the first gives 1011.

Counter: toggling stages

Wire a flip-flop's inverted output back to its own D input and it toggles on every clock edge, so its output runs at half the clock frequency. Chain four of them, each clocked by the one before, and the outputs count in binary: 0000, 0001, 0010 and on up to 1111, then wrap to 0000. Each stage divides the frequency by two.

A hardware timer is a counter driven by a clock. If a 16-bit timer counts at 1 MHz, it takes 65,536 µs (about 65.5 ms) to wrap from 65535 back to 0. That overflow can raise an interrupt, which is how periodic ticks, PWM and delays are built. A prescaler is just a counter placed before the timer to slow the clock down.