C12 · Lesson 12 · Interrupts
Letting the hardware call your code
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.
- The button on P4 raises an interrupt on each falling edge, and the ISR toggles the LED on P0. Between presses,
mainsleeps 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.
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?
40%: cycles per second, out of . 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.
Name it
What happens on an interrupt
On this board's RISC-V processor:
- A peripheral sets its flag; if its interrupt is enabled, the interrupt line goes active.
- If interrupts are enabled (the
mieregister's bit for that source and the global bit inmstatus), the processor finishes its current instruction, saves the PC inmepcand the reason inmcause, turns off further interrupts, and jumps to the address inmtvec. - 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
volatilevariables. - Protect multi-step access:
count = count + 1inmainis a load, an add and a store. If the ISR also changescountbetween 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, for an ISR of c cycles at rate f. The highest rate it can sustain is below , and lower in practice.
In MicroPython: pin.irq(handler, Pin.IRQ_FALLING); the handler runs as a soft interrupt, between Python statements.
Worked example
Main runs count = count + 1 while a timer ISR also increments count. Show how an increment can be lost.
Show the solution
- Main loads.
countis 5, and main loads 5 into a register. - The ISR runs. It fires, increments
countto 6, and returns. - Main stores. Main adds 1 to its stale 5 and stores 6.
- Count the increments. Two increments happened and
countrose by one. - 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.
Worked 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?
Show the solution
- Count the instructions. Saving and restoring take one instruction per register each way:
- The difference. That's 28 more cycles: per interrupt.
- 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.
Worked 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?
Show the solution
- The worst moment to arrive. The interrupt may arrive just as interrupts are disabled, so it waits 40 cycles.
- Enter the handler. Then it takes 12 cycles to enter:
- Keep the bound small. Keeping critical sections short is what keeps that bound small.
Answer 52 cycles, 5.2 µs.
Check
An ISR takes 200 cycles and fires 1 thousand times a second. What percentage of the 10 MHz processor does it use?
Check
An ISR takes 125 cycles. Above what interrupt rate can't the processor keep up, even doing nothing else?
Write units the way you normally would: 1.5 kHz, 1500 Hz and 0.0015 MHz are the same answer.
Check
An interrupt's response takes 12 cycles. What's the latency, at 10 MHz?
Write units the way you normally would: 1.5 µs, 1500 ns and 0.0015 ms are the same answer.
Check
An ISR saves and restores 5 registers, one instruction each way per register, and fires 1 thousand times a second. What share of the processor goes to that saving and restoring?
Check
count is 10. Main loads it, the ISR increments it and returns, then main adds 1 to its loaded copy and stores it. What is count now?
Check
An ISR runs, returns, and immediately runs again, over and over, though no new event has happened. What's the likely bug?
Check
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 on the course's RISC-V board (10 MHz, no floating point). #include "board.h" for the registers; print(x) shows a number. Tab indents; press Esc and then Tab to move on.
Check
In MicroPython, toggle the LED on P0 from a pin interrupt each time the button on P4 is pressed.
MicroPython on the course's board: machine (Pin, PWM, ADC, DAC, UART, I2C, SPI, Timer, WDT) and time. Each call into the hardware takes about 40 µs. Tab indents; press Esc and then Tab to move on.
Check
An interrupt fires 10 thousand times a second and costs 30 cycles on the 10 MHz board.
(a)
What share of the processor does it use?
(b)
At most how many thousand per second could it run, using everything?
Check
Interrupt entry takes 12 cycles, and interrupts are disabled for at most 10 cycles at a time.
(a)
What is the worst-case latency at 10 MHz?
Write units the way you normally would: 1.5 µs, 1500 ns and 0.0015 ms are the same answer.
(b)
How much of that is the critical section?
Explain why
Why must code in main that updates a variable shared with an ISR sometimes disable interrupts, even when the variable is volatile?
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
Keep practicing
10 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.