---
title: Interrupts
heading: Letting the hardware call your code
eyebrow: C12 · Lesson 12 · Interrupts
xp: 40
---

::: hook
A program that polls a button checks it millions of times for every press, and can't do anything else, or sleep, while it does. An **interrupt** turns that around: the hardware notices the event, finishes the current instruction, and jumps to a function written for it, the **interrupt service routine** (ISR). When the ISR returns, the interrupted code carries on as if nothing had happened. Interrupts let one processor respond within microseconds to many sources while sleeping the rest of the time, at the price of a new class of bugs: code that can be interrupted anywhere, sharing data with code that can run at any moment.
:::

::: play
- The button on P4 raises an interrupt on each falling edge, and the ISR toggles the LED on P0. Between presses, `main` sleeps with `__wfi()`.
- Zoom in on the press at 0.1 s: the LED changes 0.5 µs after the button's edge. That's the **latency**: finishing an instruction, jumping to the handler, saving two registers, and the store.
- Turn on the power panel: the board is asleep almost the whole time. Then delete the line that clears the flag and run it: the ISR runs again the moment it returns, forever.
:::
:::

```sim board
lang: c
attach: led P0 | blue
attach: button P4 | press 0.1..0.2 s, 0.4..0.5 s
scope: P4, P0
run: 0.6 s
show: asm, power
code:
#include "board.h"

volatile uint32_t presses = 0;

void __attribute__((interrupt)) on_irq(void) {
    GPIO_TOGGLE = 1 << 0;        // first: answer the button
    GPIO_IRQ_FLAGS = 1 << 4;     // clear the flag, or it fires again
    presses++;
}

int main(void) {
    GPIO_DIR = 1 << 0;
    GPIO_PULLUP = 1 << 4;
    GPIO_IRQ_FALL = 1 << 4;      // interrupt when P4 falls
    set_trap_handler(on_irq);
    enable_external_interrupt();
    enable_interrupts();
    while (1)
        __wfi();                 // sleep until something happens
}
```

::: predict
## An ISR takes 200 cycles and its interrupt fires 20,000 times a second. What fraction of the 10 MHz processor does it use?

- [ ] 0.2%
- [ ] 4%
- [x] 40%
- [ ] It can't keep up

::: reveal
40%: $200 \times 20\,000 = 4 \times 10^6$ cycles per second, out of $10^7$. Interrupt load adds up quickly, which is why ISRs should be short: do the urgent part (read the data, clear the flag), set a flag or put the data in a buffer, and let the main loop do the rest.
:::
:::

::: nameit
## What happens on an interrupt

On this board's RISC-V processor:

1. A peripheral sets its flag; if its interrupt is enabled, the interrupt line goes active.
2. If interrupts are enabled (the `mie` register's bit for that source and the global bit in `mstatus`), the processor finishes its current instruction, saves the PC in `mepc` and the reason in `mcause`, turns off further interrupts, and jumps to the address in `mtvec`.
3. The ISR saves the registers it will use, services the source, **clears its flag**, restores the registers and returns with `mret`, which restores the PC and re-enables interrupts.

In C, `void __attribute__((interrupt)) name(void)` makes a function an ISR: the compiler saves exactly the registers it touches (every caller-saved one if it calls a function) and ends it with `mret`. All peripherals share the external interrupt; the ISR reads `SYS_IRQ_PENDING` or each peripheral's flags to see which one fired.

## Rules for ISRs

- **Short:** read, clear, record, return. No delays, no waiting for a UART.
- **Clear the flag**, or the interrupt fires again the moment the ISR returns.
- **Share through `volatile`** variables.
- **Protect multi-step access:** `count = count + 1` in `main` is a load, an add and a store. If the ISR also changes `count` between the load and the store, its change is lost. Disable interrupts around such sequences (a **critical section**), and keep it short.

## Latency and load

**Latency** is the time from the event to the ISR's response; on this board, 5 cycles to the first useful store. **Load** is the fraction of time spent in ISRs, $c \times f / f_\text{clk}$ for an ISR of c cycles at rate f. The highest rate it can sustain is below $f_\text{clk}/c$, and lower in practice.

In MicroPython: `pin.irq(handler, Pin.IRQ_FALLING)`; the handler runs as a soft interrupt, between Python statements.
:::

::: example
## Main runs `count = count + 1` while a timer ISR also increments `count`. Show how an increment can be lost.

::: solution
1. **Main loads.** `count` is 5, and main loads 5 into a register.
2. **The ISR runs.** It fires, increments `count` to 6, and returns.
3. **Main stores.** Main adds 1 to its stale 5 and stores 6.
4. **Count the increments.** Two increments happened and `count` rose by one.
5. **The fix.** Disabling interrupts across main's three instructions prevents it.

**Answer:** if the ISR runs between main's load and its store, main writes 6 over the ISR's 6, and one increment is lost.
:::
:::

::: example
## The play's ISR saves and restores 2 registers. A version that calls a helper function must save all 16 caller-saved registers. How much longer is its overhead?

::: solution
1. **Count the instructions.** Saving and restoring take one instruction per register each way:
   $$\begin{aligned} 2 \times 2 &= 4 \\ 2 \times 16 &= 32 \end{aligned}$$
2. **The difference.** That's 28 more cycles:
   $$28 \times 100\ \text{ns} = 2.8\ \mu\text{s}$$
   per interrupt.
3. **At 10,000 interrupts a second.** That's 2.8% of the processor, spent on bookkeeping.

**Answer:** saving 16 registers adds 28 cycles, 2.8 µs, to every interrupt: 2.8% of the processor at 10,000 interrupts a second.
:::
:::

::: example
## Entering an interrupt handler takes 12 cycles, and the longest stretch with interrupts disabled is 40 cycles. What is the worst-case latency at 10 MHz?

::: solution
1. **The worst moment to arrive.** The interrupt may arrive just as interrupts are disabled, so it waits 40 cycles.
2. **Enter the handler.** Then it takes 12 cycles to enter:
   $$\begin{aligned} 40 + 12 &= 52\ \text{cycles} \\ &= 5.2\ \mu\text{s} \end{aligned}$$
3. **Keep the bound small.** Keeping critical sections short is what keeps that bound small.

**Answer:** 52 cycles, 5.2 µs.
:::
:::

::: check
given: c = 50 | 200 | 1000; f = 1 | 10 | 40
answer: 100*c*f*1000/1e7
unit: %
tolerance: 0.5%

## An ISR takes {c} cycles and fires {f} thousand times a second. What percentage of the 10 MHz processor does it use?

::: right
Right. $c f/f_\text{clk}$ = {answer}%.
:::

::: misses
- [c*f*1000/1e7] As a percentage: multiply by 100.
- [any] Not yet. Cycles per second spent, over $10^7$.
:::
:::

::: check
given: c = 40 | 125 | 400
answer: 1e7/c/1000
unit: kHz
tolerance: 0.5%

## An ISR takes {c} cycles. Above what interrupt rate can't the processor keep up, even doing nothing else?

::: right
Right. $f_\text{clk}/c$ = {answer} kHz.
:::

::: misses
- [any] Not yet. The rate at which ISRs alone fill every cycle.
:::
:::

::: check
given: n = 5 | 12 | 30
answer: n/10
unit: µs
tolerance: 0.5%

## An interrupt's response takes {n} cycles. What's the latency, at 10 MHz?

::: right
Right. {answer} µs.
:::

::: misses
- [any] Not yet. 100 ns per cycle.
:::
:::

::: check
given: k = 2 | 5 | 16; f = 1 | 10
answer: 100*2*k*f*1000/1e7
unit: %
tolerance: 0.5%

## An ISR saves and restores {k} registers, one instruction each way per register, and fires {f} thousand times a second. What share of the processor goes to that saving and restoring?

::: right
Right. $2k$ cycles per interrupt at {f} kHz: {answer}%.
:::

::: misses
- [100*k*f*1000/1e7] Count both directions: a save and a restore for each register.
- [any] Not yet. Instructions per interrupt times the rate, over $f_\text{clk}$.
:::
:::

::: check
given: a = 3 | 10 | 41
answer: a + 1
tolerance: 0

## `count` is {a}. Main loads it, the ISR increments it and returns, then main adds 1 to its loaded copy and stores it. What is `count` now?

::: right
Right. {answer}: the ISR's increment was overwritten.
:::

::: misses
- [a + 2] That's what it should be, if main's increment couldn't be interrupted.
- [any] Not yet. Main stores its stale value plus 1.
:::
:::

::: check
kind: choice

## An ISR runs, returns, and immediately runs again, over and over, though no new event has happened. What's the likely bug?

- [ ] The ISR isn't marked volatile
- [x] The ISR never clears the peripheral's flag
- [ ] Interrupts are disabled in main
- [ ] The ISR is too short

::: misses
- [1] Variables are volatile, not functions; and that wouldn't cause re-entry.
- [3] Then the ISR wouldn't run at all.
- [4] Short ISRs are good.
:::
:::

::: check
kind: c
attach: led P0; button P4 | press 0.1..0.15 s, 0.3..0.35 s, 0.5..0.55 s
run: 0.7
expect: edges(P0) = 3; first(P0) = 0.1 s ± 0.05%; current < 3 mA

## Toggle the LED on P0 from an interrupt each time the button on P4 (to ground) is pressed, and sleep with `__wfi()` the rest of the time.

```c starter
#include "board.h"

int main(void) {
    GPIO_DIR = 1 << 0;
    GPIO_PULLUP = 1 << 4;
    int last = 1;
    while (1) {
        int now = (GPIO_IN >> 4) & 1;
        if (now != last && !now) GPIO_TOGGLE = 1 << 0;
        last = now;
    }
}
```

```c solution
#include "board.h"

void __attribute__((interrupt)) on_irq(void) {
    GPIO_IRQ_FLAGS = 1 << 4;
    GPIO_TOGGLE = 1 << 0;
}

int main(void) {
    GPIO_DIR = 1 << 0;
    GPIO_PULLUP = 1 << 4;
    GPIO_IRQ_FALL = 1 << 4;
    set_trap_handler(on_irq);
    enable_external_interrupt();
    enable_interrupts();
    while (1)
        __wfi();
}
```

::: right
Right. The polling version works too, but keeps the processor awake at full current; this one sleeps.
:::
:::

::: check
kind: micropython
attach: led P0; button P4 | press 0.1..0.15 s, 0.3..0.35 s, 0.5..0.55 s, 0.7..0.75 s
run: 0.9
expect: edges(P0) = 4

## In MicroPython, toggle the LED on P0 from a pin interrupt each time the button on P4 is pressed.

```micropython starter
from machine import Pin
import time

led = Pin(0, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)
while True:
    time.sleep_ms(100)
```

```micropython solution
from machine import Pin
import time

led = Pin(0, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)
button.irq(lambda p: led.toggle(), Pin.IRQ_FALLING)
while True:
    time.sleep_ms(100)
```

::: right
Right. The handler runs on each falling edge while the main loop sleeps.
:::
:::

::: check
kind: parts
given: r = 1 | 10 | 50; c = 30 | 80 | 200

## An interrupt fires {r} thousand times a second and costs {c} cycles on the 10 MHz board.

::: part
answer: r*1000*c/1e7*100
unit: %
tolerance: 0.5%

### What share of the processor does it use?

::: misses
- [any] Rate × cycles ÷ clock.
:::
:::

::: part
answer: 1e7/c/1000
tolerance: 0.5%

### At most how many thousand per second could it run, using everything?

::: misses
- [any] Clock ÷ cycles.
:::
:::
:::

::: check
kind: parts
given: e = 8 | 12 | 20; d = 10 | 40 | 150

## Interrupt entry takes {e} cycles, and interrupts are disabled for at most {d} cycles at a time.

::: part
answer: (e + d)/10
unit: µs
tolerance: 0.5%

### What is the worst-case latency at 10 MHz?

::: misses
- [e/10] The interrupt may wait out a disabled stretch first.
- [any] (entry + disabled) ÷ 10 MHz.
:::
:::

::: part
answer: d/10
unit: µs
tolerance: 0.5%

### How much of that is the critical section?

::: misses
- [any] Its cycles ÷ 10 MHz.
:::
:::
:::

::: explain
## Why must code in `main` that updates a variable shared with an ISR sometimes disable interrupts, even when the variable is volatile?

::: model
`volatile` makes the compiler perform every load and store, but an update like `count = count + 1` is still several instructions: load, add, store. An interrupt can arrive between the load and the store; if its ISR changes `count`, main then stores a value computed from the old copy, overwriting the ISR's change. Disabling interrupts for those few instructions makes the sequence indivisible from the ISR's point of view, so neither update can be lost. The critical section has to be short, because every cycle interrupts are off adds to the latency of whatever interrupt arrives meanwhile.
:::
:::

::: practice

::: check
given: c = 80 | 600; f = 5 | 20
answer: 100*c*f*1000/1e7
unit: %
tolerance: 0.5%

## Load of a {c}-cycle ISR at {f} kHz?

::: misses
- [any] $c f/f_\text{clk}$.
:::
:::

::: check
given: c = 100 | 250 | 500 | 1000 | 2000 | 5000
answer: 1e7/c/1000
unit: kHz
tolerance: 0.5%

## Highest rate for a {c}-cycle ISR?

::: misses
- [any] $f_\text{clk}/c$.
:::
:::

::: check
given: n = 5 | 8 | 12 | 20 | 30 | 50 | 100
answer: n/10
unit: µs
tolerance: 0.5%

## Latency of {n} cycles?

::: misses
- [any] 100 ns per cycle.
:::
:::
:::
