ROBOTICS 101Concept explainer

Microcontroller Loops and Interrupts

A microcontroller program usually runs one main loop: read sensors, do some math, send commands, repeat. If it only checks the encoder pin once per loop, fast pulses slip by unseen. An interrupt makes the hardware stop the main loop the instant a pulse arrives.

When polling misses pulses

A loop that checks the pin every \(T_{\text{loop}}\) seconds can only see changes slower than its check rate. For a square wave of frequency \(f\), polling sees every pulse only if it checks at least twice per pulse:

$$T_{\text{loop}} < \frac{1}{2f}$$

An interrupt runs a short handler on every edge. It keeps up as long as each handler finishes before the next edge, so its limit is \(f < 1 / T_{\text{handler}}\).

What to notice

With a 2 ms loop, polling keeps up at a couple of hundred pulses per second, but at 600 per second it already misses many. The interrupt count stays exact until the pulse rate gets near the handler's own limit, here 100,000 per second for a 10 µs handler. Handlers must stay short: no printing, no long math, just count and return.

For very fast encoders, many microcontrollers have a hardware counter or a quadrature decoder that counts pulses with no code running at all.