Interrupts in Embedded Systems Explained
Imagine reading a book while waiting for a delivery. You could look up from the page every few seconds to check the door, which wastes effort and risks missing the knock. Or you could keep reading and let the doorbell tell you when someone arrives. Interrupts give a microcontroller the doorbell.
An interrupt is a signal that tells the processor to pause what it is doing, handle an urgent event, and then return to its previous work exactly where it left off. Interrupts are central to almost every embedded system, because real devices must respond to buttons, timers, serial data and sensors without wasting time.
Polling Versus Interrupts
There are two basic ways to learn that something has happened.
- Polling: The program repeatedly checks a flag or pin in a loop. It is simple and predictable, but it burns processor time and delays other work. If a loop takes a long time to come around, brief events can be missed.
- Interrupts: The hardware notifies the processor the moment the event occurs. The main code can do other tasks, or sleep to save power, until needed.
Polling works well for slow, simple systems. Interrupts are better when response time matters, when events are rare but important, or when power use must stay low.
What Happens During an Interrupt
The sequence is handled mostly by hardware.
- A peripheral raises an interrupt request, for example when a pin changes level, a timer overflows or a byte arrives.
- If interrupts are enabled and the request is allowed, the processor finishes the current instruction.
- It saves its context, which includes the program counter and some registers, so it can resume later.
- It looks up the address of the matching handler in the interrupt vector table and jumps there.
- The interrupt service routine (ISR) runs and deals with the event.
- A return-from-interrupt instruction restores the saved context, and the main program continues as if nothing happened.
The time between the event and the first instruction of the ISR is the interrupt latency. Keeping it short and predictable is a key design goal.
Common Interrupt Sources
- External pins: A button press, a sensor alert line or a signal edge.
- Timers: Fire at regular intervals or when a count is reached, used for scheduling and measuring time.
- Serial peripherals: Signal that a byte was received or that the transmit buffer is empty.
- ADC: Reports that a conversion has finished.
- Direct memory access (DMA): Signals that a block transfer is complete.
- Faults and exceptions: Reset, invalid instruction or bus errors.
Enabling, Masking and Priorities
Interrupts can be turned on and off at several levels. Each peripheral has its own enable bit, and the processor has a global interrupt enable. Disabling an interrupt is called masking.
Most microcontrollers also support priorities. When two interrupts occur at the same time, the higher priority runs first. Some processors allow nested interrupts, in which a higher priority interrupt can interrupt a running lower priority ISR. Nesting improves responsiveness, but makes the system harder to reason about.
Rules for Writing Good ISRs
An ISR runs at a special time and can disturb the rest of the program, so discipline matters.
- Keep it short. Do the minimum, such as reading a register, setting a flag or storing a byte in a buffer. Leave heavy work to the main loop.
- Do not wait. Avoid delays, long loops, and blocking calls inside the ISR.
- Clear the interrupt flag if your hardware requires it, or the ISR will fire again immediately.
- Avoid slow operations such as formatted printing, memory allocation, or floating-point math on small cores.
- Mark shared variables as volatile. The compiler may otherwise keep a value in a register and never notice that the ISR changed it.
- Protect shared data. If a variable bigger than the processor's native word size is read in the main loop, an interrupt may change it halfway through. Briefly disable interrupts, or use atomic operations, during the read.
A typical pattern looks like this:
volatile uint8_t button_pressed = 0;
void EXTI_IRQHandler(void) {
clear_interrupt_flag();
button_pressed = 1;
}
int main(void) {
setup();
while (1) {
if (button_pressed) {
button_pressed = 0;
handle_button();
}
}
}
The handler only sets a flag. The real work happens in the main loop, where timing is less critical.
Common Pitfalls
- Switch bounce: A mechanical button can trigger many interrupts in a row. Use hardware filtering or ignore repeated events for a short time.
- Race conditions: Main code and an ISR use the same data without protection.
- Stack overflow: Deeply nested interrupts can consume more stack than expected.
- Priority inversion and starvation: A busy high priority interrupt prevents others from running.
- Missing the flag clear: The ISR is called again and again, freezing the program.
Using Interrupts to Save Power
Many microcontrollers can enter a deep sleep mode and wake up on an interrupt. A device that spends most of its time asleep, waking only for a timer tick or a sensor event, can run on a small battery for a very long time. This is one of the biggest practical advantages over polling.
Frequently Asked Questions
What is an interrupt vector table?
It is a list in memory that holds the starting address of each interrupt handler. When an interrupt occurs, the processor reads the entry for that source and jumps to the address stored there.
Can an ISR call other functions?
Yes, but only short and safe ones. Functions that block, allocate memory or are not designed to be reentrant can cause trouble. Keep the work minimal and defer anything complex to the main program.
What is the difference between an interrupt and an exception?
Interrupts are usually caused by external or peripheral events and happen asynchronously. Exceptions arise from the processor's own activity, such as dividing by zero or accessing invalid memory. Many architectures handle both through the same vector mechanism.