Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 37 ยท Interrupts and Timers

Interrupts and Interrupt Service Routines

Learn how microcontroller interrupts work: vector tables, priorities, nesting, latency, and how to write short interrupt service routines that hand work to main.

A microcontroller spends most of its life waiting: for a button, for a byte on a serial line, for a timer to expire, for an analog converter to finish. There are two ways to wait. You can poll, which means the program keeps asking "has it happened yet?" in a loop. Or you can let the hardware interrupt the CPU: the program does other work, and when the event happens, the CPU pauses what it was doing, runs a small function for the event, and then continues exactly where it stopped.

Interrupts are the heart of embedded programming. They give you fast reaction to events without wasting cycles, and they let a sleeping CPU wake up only when there is something to do. They are also the source of the hardest embedded bugs, so this chapter treats them carefully. In this lesson you will learn what happens during an interrupt, what the vector table is, how priorities work, and the rules for writing a good interrupt service routine (ISR).

Polling versus interrupts

Polling is simple. Reading a status register in a loop works fine when the CPU has nothing else to do, or when the event is guaranteed to arrive soon:

C
// Board-specific, read-only: wait for a UART byte by polling
while ((UART->STATUS & UART_RX_READY) == 0) {
    /* spin */
}
uint8_t b = UART->DATA;

The cost is that the CPU is fully busy, burns power, and can miss other events while it spins. If you also had to blink an LED every 10 ms, you would have to sprinkle that check into every wait loop.

With interrupts, the peripheral raises a signal when its event occurs. The CPU finishes the current instruction, saves a little state, and jumps to the ISR. When the ISR returns, the interrupted code continues as if nothing had happened.

Polling Interrupt-driven
Reaction time Depends on how often you check Short and bounded (tens of cycles)
CPU usage Busy while waiting Free to do other work or sleep
Code structure Simple, linear Asynchronous, needs care with shared data
Typical use Short waits, startup, very simple programs Real-time events, communication, low power

What the CPU does on an interrupt

The sequence is almost the same on every architecture. The diagram shows the steps for an ARM Cortex-M, where the hardware does most of the work for you.

flowchart TD
    A["Peripheral sets its pending flag"] --> B["Interrupt controller checks: enabled? priority high enough?"]
    B --> C["CPU finishes current instruction"]
    C --> D["Hardware pushes registers and return address on the stack"]
    D --> E["CPU reads the handler address from the vector table"]
    E --> F["ISR runs"]
    F --> G["Return from interrupt: registers restored"]
    G --> H["Main code continues"]

The interrupted code never knows it was paused, as long as the ISR leaves its registers alone.

The key pieces:

  • Interrupt request (IRQ): a signal from a peripheral or an external pin. Each source has its own number.
  • Pending flag: a bit that remembers the request until the CPU serves it. If the same event happens again before service, the flag is already set, so the two events become one. This is why interrupts can be lost.
  • Enable bits: each source can be enabled in the peripheral itself and again in the interrupt controller. There is usually a global switch as well (PRIMASK on Cortex-M, the I flag on AVR).
  • Vector table: an array in memory (usually in flash) with one handler address per interrupt number. The CPU indexes it with the IRQ number to find the code to run.
  • Context saving: the CPU must preserve whatever the ISR could change. Cortex-M pushes eight registers automatically. On 8-bit AVR the compiler generates the push and pop instructions inside the ISR prologue.
  • Latency: the time between the event and the first instruction of the ISR. It includes finishing the current instruction, stacking, and any delay while a higher-priority ISR or a critical section blocks it. Real-time designs budget for the worst case, not the average.

Simulating a vector table

You cannot raise a real interrupt on this website, but the mechanism is just an array of function pointers and a bit mask, and you can model it in plain C. The program below keeps a pending mask, a vector table, and a dispatcher that serves the lowest-numbered pending interrupt first. Lower number means higher priority, which is the convention on ARM Cortex-M.

C A tiny interrupt controller simulation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice the order: TIMER (0), then BUTTON (2), then ADC_DONE (3), regardless of the order in which they were raised. And notice that raising UART_RX twice produced a single run. A pending flag is one bit, not a counter. If you must not lose events, the ISR has to be fast enough, or the peripheral needs a hardware buffer (a FIFO) or a DMA channel.

Priorities and nesting

When two interrupts are pending, the controller picks the more urgent one. When a new request arrives while an ISR is running, the rule is:

  • If the new request has higher priority than the running ISR, it preempts it. This is called nesting.
  • Otherwise it waits in the pending state until the running ISR finishes.

Cortex-M chips let you assign a numeric priority to each interrupt, where a smaller number means more urgent. Simple 8-bit parts such as the classic AVR have fixed priorities (the vector order) and no nesting by default.

Nesting lowers the latency of urgent events but makes the worst-case stack depth larger and the data-sharing rules harder. A common, safe design is to give every ISR the same priority level (so none nests) and keep each one very short.

The rules for writing an ISR

  1. Keep it short. Do the minimum that cannot wait: read the data register, clear the flag, store the value, set a flag for main. Everything else belongs in the main loop or a task.
  2. Never block. No waiting for another event, no delay loops, no waiting on a lock that main might hold.
  3. Clear the source. Most peripherals keep requesting until you acknowledge them. Forgetting this leaves the CPU stuck re-entering the same ISR forever.
  4. Avoid slow or non-reentrant calls. printf, malloc and floating-point math are poor choices inside an ISR: they are slow, may use locks, and may use shared state.
  5. Share data carefully. Any variable written in an ISR and read elsewhere must be volatile, and multi-byte values need protection. The lesson on volatile and shared data covers this properly.
  6. Know your return rules. On many chips an ISR is a normal-looking function with a special attribute; on others the compiler must be told to use the return-from-interrupt instruction.

A real handler looks like this. It is a board-specific sketch for an STM32-style chip, shown read-only:

C
// Read-only: typical Cortex-M handler (names depend on your vendor headers)
volatile uint8_t rx_byte;
volatile bool    rx_ready;

void USART2_IRQHandler(void) {
    if (USART2->ISR & USART_ISR_RXNE) {   // is this the receive event?
        rx_byte  = (uint8_t)USART2->RDR;  // reading RDR also clears RXNE
        rx_ready = true;                  // tell main there is work
    }
}

The flag-and-main-loop pattern

The most common structure is "ISR sets a flag, main does the work". The ISR runs in microseconds and the slow processing happens at a time that suits the program. The simulation below plays a hardware timer that ticks every step and a button that is pressed at steps 3 and 7. The "ISR" functions are ordinary calls here, but the structure is identical to the real thing.

C ISR sets a flag, main loop handles it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Try changing the button steps to 3 and 3. The second press disappears because a flag cannot count. If presses can arrive faster than main handles them, replace the flag with a counter or, better, a queue (you will build one in the shared data lesson).

Common mistakes

  • Doing too much in the ISR. A 2 ms handler on a 1 kHz interrupt leaves no time for anything else.
  • Not clearing the interrupt flag. The ISR returns and immediately fires again.
  • Forgetting volatile. The compiler may cache the flag in a register and main never sees the change.
  • Calling a function that is not safe in an ISR, such as printf or a blocking driver call.
  • Enabling an interrupt before its handler and data are ready. Initialize everything first, then enable.
  • Ignoring stack use. Nested ISRs plus deep call chains overflow the stack silently.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the vector table hold?

    The CPU uses the interrupt number as an index into the table and jumps to the address stored there.
  2. 2. Two events from the same peripheral occur before the CPU serves the first. With a single pending bit, what usually happens?

    A pending flag only remembers that something happened, not how many times, so the two requests merge into one.
  3. 3. Which is the best use of an ISR?

    ISRs should do only the work that cannot wait and hand the rest to the main loop.
  4. 4. An ISR never clears its peripheral's interrupt flag. What is the likely result?

    The request line stays active, so the controller re-enters the ISR as soon as it returns.

Summary

  • Interrupts let hardware events pause the CPU, run a short handler and resume, which saves power and gives fast reaction.
  • The vector table maps interrupt numbers to handlers; a pending bit remembers a request but does not count events.
  • Priorities decide which pending interrupt runs first and whether one may nest inside another.
  • Keep ISRs short, never block, clear the source, and hand heavy work to the main loop with a flag or queue.

Next: Timers, Counters and PWM