An interrupt service routine (ISR), also called an interrupt handler, is a function the hardware calls automatically when an event happens. Examples include a timer expiring, a byte arriving on a UART, or a pin changing level. Interrupts let firmware react quickly without polling everything in a loop. They also introduce concurrency, which is where most interrupt bugs come from.
This guide walks through writing an ISR in C on common microcontrollers. It covers the setup steps people often miss and the rules that keep handlers reliable.
What happens when an interrupt fires
The details vary by architecture, but the sequence is broadly the same:
- A peripheral sets an interrupt flag and, if that interrupt is enabled, signals the interrupt controller.
- The CPU finishes (or, on some cores, abandons and later restarts) the current instruction.
- The CPU saves context: at least the program counter and status register, and on some cores more registers.
- It looks up the handler’s address in the vector table, a table of function addresses with one entry per interrupt source.
- It runs your ISR.
- When the ISR returns, the saved context is restored and the interrupted code continues as if nothing happened.
On Arm Cortex-M, the hardware automatically saves registers r0–r3, r12, LR, PC and xPSR when the interrupt is taken. That’s why a Cortex-M handler can be an ordinary C function with no special keyword. On other architectures, the compiler needs a keyword or attribute so it generates the extra save/restore code and the special return instruction.
Step 1: Find the handler name for your chip
| Platform | How you declare an ISR |
|---|---|
| Arm Cortex-M (CMSIS, e.g., STM32, NXP, Nordic) | A plain function whose name matches the vector table in the startup file: void TIM2_IRQHandler(void) |
| AVR (avr-gcc / avr-libc) | The ISR() macro with a vector name: ISR(TIMER0_COMPA_vect) |
| PIC (Microchip XC8) | A function marked as an interrupt: void __interrupt() isr(void) |
| ESP32 (ESP-IDF) | A normal function registered at run time, for example with gpio_isr_handler_add(), usually marked IRAM_ATTR so it runs from internal RAM |
On Cortex-M, the startup file defines every handler as a weak alias of a default handler, which is usually an infinite loop. When you write a function with exactly the same name, yours replaces the default at link time. If you misspell the name (TIM2_IRQHandle, or the wrong case), the code still compiles and links, but the interrupt jumps into the default infinite loop. Always copy handler names from your startup file.
Step 2: Enable the interrupt at every level
An interrupt only reaches your handler if it’s enabled at each level:
- In the peripheral. Set the peripheral’s interrupt-enable bit, such as a timer’s update-interrupt enable or a UART’s receive-not-empty enable.
- In the interrupt controller. On Cortex-M, enable the line in the NVIC and set its priority.
- Globally. The CPU’s global interrupt mask must allow interrupts. Cortex-M starts with interrupts globally enabled. On AVR you call
sei().
Forgetting one of these three levels is the most common reason an ISR “never runs.”
Step 3: Write the handler
A good handler does the minimum. It confirms the source, clears the flag, captures data or sets a flag, and returns.
Example: STM32 external interrupt
This example responds to a rising edge on pin PA0 (the user button on STM32F4 Discovery boards) using register-level code and CMSIS:
#include <stdbool.h>
#include "stm32f4xx.h"
static volatile bool button_event = false;
static void button_irq_init(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; /* clock for GPIOA */
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; /* clock for SYSCFG */
/* PA0 is an input after reset. Route EXTI line 0 to port A. */
SYSCFG->EXTICR[0] &= ~SYSCFG_EXTICR1_EXTI0;
EXTI->IMR |= EXTI_IMR_MR0; /* unmask line 0 (peripheral level) */
EXTI->RTSR |= EXTI_RTSR_TR0; /* trigger on rising edge */
NVIC_SetPriority(EXTI0_IRQn, 5); /* interrupt controller level */
NVIC_EnableIRQ(EXTI0_IRQn);
}
void EXTI0_IRQHandler(void)
{
if (EXTI->PR & EXTI_PR_PR0) {
EXTI->PR = EXTI_PR_PR0; /* write 1 to clear: use =, not |= */
button_event = true;
}
}
int main(void)
{
button_irq_init();
for (;;) {
if (button_event) {
button_event = false;
/* handle the press here, outside the ISR */
}
}
}
A few details are worth noticing:
button_eventisvolatile, because it’s shared between the ISR andmain(). Without it, an optimized build may never see the change. The volatile keyword guide explains why.- The pending register is write-1-to-clear, so you write the bit with
=. Using|=would read the register and write back every pending bit, clearing other lines’ flags too. See bit manipulation in embedded C for more on this trap. - Mechanical buttons bounce, so a real design debounces the input, either with a timer or with a small state machine.
- Register names differ between STM32 families. Newer families, for example, split the EXTI pending register into rising and falling registers. Check your reference manual.
Example: AVR timer interrupt
On an ATmega328P at 16 MHz, this sets up Timer0 to interrupt every 1 ms:
#include <avr/io.h>
#include <avr/interrupt.h>
volatile uint32_t ms_ticks;
ISR(TIMER0_COMPA_vect)
{
ms_ticks++;
}
static void timer0_init(void)
{
TCCR0A = (1 << WGM01); /* CTC mode */
OCR0A = 249; /* 16 MHz / 64 / 250 = 1 kHz */
TCCR0B = (1 << CS01) | (1 << CS00); /* prescaler 64, starts the timer */
TIMSK0 = (1 << OCIE0A); /* enable compare-match A interrupt */
sei(); /* global interrupt enable */
}
On AVR, this timer’s flag is cleared automatically when the CPU jumps to the vector. Many other peripherals, on AVR and elsewhere, require you to clear the flag yourself. The datasheet section for each interrupt tells you which kind it is.
Because ms_ticks is 32 bits and the AVR is an 8-bit CPU, main code must read it with interrupts briefly disabled, or it may see a half-updated value. See the section on protecting shared data below.
Rules for a good ISR
- Keep it short. While your ISR runs, other interrupts of the same or lower priority wait. Long handlers add latency to everything else.
- Don’t block. No delay loops, no waiting for flags, no polling other peripherals for long periods.
- Avoid heavy library calls.
printf,mallocand many C library functions are slow, may not be reentrant, and may use locks. - Clear the interrupt source. If you don’t, the interrupt fires again the moment you return, and the main code never runs.
- Clear the flag early. On some Cortex-M parts, a flag cleared in the last instruction before returning may not be cleared yet by the time the core checks for pending interrupts. That’s because the write takes time to travel across the peripheral bus. The result is that the handler runs a second time. Clearing at the start of the handler, or reading the register back after clearing, avoids this.
- Use
volatilefor shared variables, and protect anything that isn’t updated in a single access. - Don’t call non-reentrant functions that main code may also be in the middle of.
- Be careful with floating point. On cores with an FPU, saving FPU registers adds latency (Cortex-M4F and M7 use “lazy stacking” to reduce this). On cores without an FPU, floating-point math in an ISR is very slow.
Getting data out of an ISR
A flag
For “something happened” events, a volatile bool set in the ISR and cleared in main code (as in the button example) is often enough. If events can arrive faster than main code handles them, use a counter or a queue instead, because a flag merges multiple events into one.
A ring buffer
For streams of data, such as UART receive, a single-producer, single-consumer ring buffer works well. The ISR only writes the head index and main code only writes the tail index, so neither side needs to disable interrupts:
#include <stdbool.h>
#include <stdint.h>
#define RB_SIZE 64u /* must be a power of two */
static volatile uint8_t rb_data[RB_SIZE];
static volatile uint8_t rb_head; /* written only by the ISR */
static volatile uint8_t rb_tail; /* written only by main code */
void USART2_IRQHandler(void)
{
if (USART2->SR & USART_SR_RXNE) {
uint8_t byte = (uint8_t)USART2->DR; /* reading DR clears RXNE */
uint8_t next = (uint8_t)((rb_head + 1u) & (RB_SIZE - 1u));
if (next != rb_tail) { /* drop the byte if full */
rb_data[rb_head] = byte;
rb_head = next;
}
}
}
bool rb_get(uint8_t *out)
{
if (rb_tail == rb_head) {
return false; /* empty */
}
*out = rb_data[rb_tail];
rb_tail = (uint8_t)((rb_tail + 1u) & (RB_SIZE - 1u));
return true;
}
The indices are uint8_t, so reads and writes of them are single accesses even on 8-bit CPUs. The same pattern works for transmit, with the roles reversed.
Protecting shared data in main code
When main code reads or modifies data that an ISR also touches, and the access isn’t a single atomic load or store, wrap it in a short critical section:
/* Arm Cortex-M (CMSIS) */
uint32_t primask = __get_PRIMASK();
__disable_irq();
uint32_t ticks_copy = shared_ticks; /* or a read-modify-write */
__set_PRIMASK(primask); /* restore, don't blindly re-enable */
On AVR, ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { ... } from <util/atomic.h> does the same. Keep critical sections as short as possible, because every cycle with interrupts disabled adds latency.
Priorities, nesting and RTOS rules
On Cortex-M, the NVIC lets a higher-priority interrupt preempt a lower-priority one that’s already running. A lower priority number means a higher priority, so 0 is the most urgent. Chips implement only some of the priority bits. Many STM32 parts implement 4 bits, giving 16 levels. NVIC_SetPriority() takes care of shifting the value into the implemented bits.
Guidelines:
- Give the highest priority to interrupts with the tightest timing needs, not necessarily the most “important” ones.
- Interrupts that share data shouldn’t be able to preempt each other mid-update, so either give them the same priority or protect the shared data.
With an RTOS, there are extra rules. In FreeRTOS, for example:
- Only call API functions ending in
FromISR(such asxQueueSendFromISR()) from interrupt handlers. - On Cortex-M ports, interrupts that call FreeRTOS APIs must have a priority at or below (numerically at or above)
configMAX_SYSCALL_INTERRUPT_PRIORITY. - Use the “higher priority task woken” result and
portYIELD_FROM_ISR()so a task woken by the ISR runs right away.
A common RTOS design keeps the ISR tiny: it captures data, sends a notification or queue item, and lets a task do the processing.
Measuring how long your ISR takes
Two practical methods:
- GPIO toggle. Set a spare pin high at the start of the ISR and low at the end, then measure the pulse with an oscilloscope or logic analyzer. You also see how often it runs and how much it jitters.
- Cycle counter. On Cortex-M3 and higher, the DWT cycle counter (
DWT->CYCCNT) can timestamp the entry and exit of the handler, once it’s enabled. Not every chip implements it, and Cortex-M0/M0+ doesn’t have it.
When the ISR doesn’t run (troubleshooting)
- The handler name doesn’t match the vector table. Check the startup file.
- One enable level is missing: the peripheral enable, the NVIC enable, or the global enable.
- The peripheral clock isn’t enabled, so register writes to it are ignored.
- The pin isn’t routed to the interrupt line, for example in the EXTI/SYSCFG mapping on STM32.
- The handler runs constantly because the flag is never cleared, or is cleared too late.
- It lands in the default handler or a HardFault, typically because of a misspelled name or a crash inside the ISR.
Set a breakpoint inside the handler, and inspect the peripheral’s flag registers and the NVIC pending/enable registers with a debugger. The walkthrough in debugging microcontrollers with JTAG, SWD and GDB covers how to do that.
Writing ISRs in C++
C++ compilers mangle function names, so a C++ function called TIM2_IRQHandler won’t match the C symbol in the vector table, and the weak default handler will be used instead. Declare handlers with C linkage:
extern "C" void TIM2_IRQHandler(void)
{
/* ... */
}
Checklist
- Handler name copied exactly from the startup file or vector list
- Interrupt enabled in the peripheral, in the interrupt controller, and globally
- Source confirmed and flag cleared early (with
=for write-1-to-clear registers) - Handler is short, non-blocking and free of heavy library calls
- Shared variables declared
volatile, with multi-byte or read-modify-write accesses protected - Data passed out through flags, counters, ring buffers or RTOS
FromISRcalls - Priorities chosen deliberately, and RTOS priority limits respected
- Execution time measured on real hardware
Interrupts pair naturally with event-driven designs. Once your ISRs produce events, a state machine in embedded C is a clean way to consume them. For the broader context of how ISRs fit into firmware structure, see the embedded firmware development overview.