What is an interrupt? Handling events without constant polling
Atlasbot · 20/8/2026 · 10 min read
Counting encoder pulses by calling digitalRead() repeatedly during loop() (called polling) has an obvious problem: if loop() is busy doing something else (e.g. sending data via UART) at the exact moment the encoder pulse appears, that pulse can be missed completely. Interrupt solves this problem — allowing the MCU to react immediately when an event occurs, regardless of what the main program is doing.
Polling vs Interrupt
- Polling — main program keeps asking "is there an event yet?" in loop. Simple, straightforward, but consumes CPU (checks continuously even when nothing happens) and can miss short events if the program is busy with something else.
- Interrupt — the hardware automatically "notifies" the CPU as soon as an event occurs (eg: GPIO pin changes from LOW to HIGH), the CPU pauses the running program, jumps in to run a separate processing function (ISR — Interrupt Service Routine), then returns to the right place where it just stopped.
In short: Polling = proactively asking continuously, you may miss out. Interrupt = passively waiting to be "called", not missing the event even though the main program is busy with something else.
Types of interrupt triggers on GPIO pins
Interrupts on GPIO pins are typically configured according to which signal change will trigger:
| Trigger type | When to activate |
|---|---|
RISING | Foot moves from LOW to HIGH |
FALLING | Foot moves from HIGH to LOW |
CHANGE | Pin changes state in any direction (both RISING and FALLING) |
Reading a quadrature encoder (2 channels A/B) usually requires CHANGE on both channels to not miss any pulse edges, enough data to determine both speed and direction of rotation.
Technical details
Formulas
The interrupt pulse frequency that the MCU must handle depends on the encoder resolution (number of pulses/revolution) and the actual rotation speed — this number determines whether the MCU can "keep up" or not:
f (Hz) = (Number of pulses/revolution × Rotation speed (rpm)) / 60
For example: encoder 500 pulses/rev, motor rotates 3000 rpm
f = (500 × 3000) / 60 = 25.000 Hz = 25kHz
→ MCU must finish processing an interrupt in less than 1/25,000s ≈ 40µs, otherwise it will start missing pulses
Parameters
The number of pins that support external interrupts varies significantly between boards — directly affecting how many encoders can be read at the same time using hardware interrupts:
| Board/Chip | Number of pins that support external interrupt |
|---|---|
| Arduino Uno | Only 2 pins (D2, D3 — INT0/INT1 respectively) |
| STM32 | Almost every GPIO pin (via EXTI, see below) |
| ESP32 | Almost every GPIO pin |
Register / Bit / Byte
On the ARM Cortex-M series microcontroller (STM32), interrupts are managed through two layers: EXTI (External Interrupt/Event Controller) decides which GPIO pin and what type of trigger (rising/falling) will generate an interrupt request, while NVIC (Nested Vectored Interrupt Controller) is the central coordinator that decides which interrupt is received. Prioritizes processing when multiple interrupts occur nearly simultaneously — each interrupt has a configurable priority, with higher priority interrupts able to preempt lower-priority interrupts that are in progress.
Practical applications
The 4-wheel robot (Mecanum Robot) needs to simultaneously read 4 encoders (1 for each wheel) at high speed to calculate odometry (real-time robot position estimation) fed to ROS2 — if polling is used, the main loop can only read each encoder in turn, easily skewing the sampling time between wheels and distorting the calculation of the combined velocity. Using interrupts on all encoder pins ensures that each pulse is recorded at the exact time it occurs, regardless of whether the main program is busy processing UART/ROS2 communication or PID calculations.
Practical example: counting encoder pulses using interrupt
volatile long encoderCount = 0; // volatile: required for variables shared with ISR
void onEncoderA() {
bool b = digitalRead(PIN_ENCODER_B);
encoderCount += (digitalRead(PIN_ENCODER_A) == b) ? 1 : -1;
}
void setup() {
pinMode(PIN_ENCODER_A, INPUT_PULLUP);
pinMode(PIN_ENCODER_B, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_ENCODER_A), onEncoderA, CHANGE);
}
void loop() {
Serial.println(encoderCount); // Reads the enumeration value, updating it even while loop() is doing something else
delay(100);
}
attachInterrupt() registers function onEncoderA to run automatically every time encoder A pin changes state — even though loop() is in the middle of command delay(100), the encoder pulses are still counted correctly, which cannot guarantee if using digitalRead() in loop() normally.
Rules for writing ISR (Interrupt Service Routine)
- Keep ISR as short as possible — while the ISR is running, other interrupts (depending on configuration) may be suppressed; A long ISR causes the system to lose its ability to respond promptly to other events.
- Do not call
delay()in ISR —delay()relies on the internal timer which the interrupt itself can affect, causing hangs or undefined behavior. - Variables shared between the ISR and the main program must be declared
volatile— otherwise, the compiler may optimize in a way that assumes the variable remains constant between reads inloop(), resulting in reading the old value even though the ISR has been updated. - Avoid
Serial.print()in ISR — UART communication functions are generally unsafe to call in interrupt context (not "interrupt-safe"), which can cause program crashes.
Common mistakes
- Forgot
volatilefor variable shared with ISR — program runs inexplicably wrong: ISR runs correctly, variable actually changes value in memory, butloop()still reads the old value due to incorrect optimization by the compiler. - Debounce mechanical push button — the mechanical contact of a push button often "bounces" (bounces) for a few milliseconds when pressed/released, causing a single press to actually trigger the ISR multiple times in a row — additional debounce logic is needed (e.g. skip the event if less than a few dozen milliseconds from the previous event) if using an interrupt for the push button instead of an encoder.
- ISR is too long or computationally intensive — placing all the complex processing logic in the ISR instead of just updating a flag/counter variable and then processing the details in
loop()— makes the system react slowly to other events. - Limited number of interrupt support pins — not all GPIO pins support interrupts (especially on older Arduino boards with only 2 external interrupt pins) — check the board documentation before designing a circuit that relies on an interrupt on a specific pin.
Conclusion
Interrupts are a must-have tool when you need to react accurately, without missing a beat, to high-frequency or unpredictable timing events — most typically reading encoders in robots. Mastering the rules of writing concise ISRs and using volatile in the right place can avoid most of the most difficult to debug errors when new to interrupts. This is also the last article in the Fundamental Knowledge section — these concepts will be reused continuously in the following sections about specific electronic components and microcontrollers.
Get new articles and lessons by email
When a new technical article or course module is published, Atlas Robotics sends you a short email. No spam.
Unsubscribe any time with the link in each email. See our Privacy policy.