The idea: urgent work cuts in, the stack remembers where to go back
A microcontroller has several things that can interrupt it: a timer, a button on a pin, a byte arriving on the serial port. Each one has an interrupt service routine (ISR) and a priority level. On this page level 0 is the most urgent and main runs below every level. When a request comes in, the CPU asks one question at the end of each instruction: is this more urgent than what I am doing now? If yes, it saves where it was and jumps to the ISR, even if it is already inside another ISR. That is nesting. If no, the request stays pending until the CPU drops to a lower level. The page counts every cycle, so you can see what each step costs. How a PC's interrupt controller and iret work is on interrupt-driven I/O; how a MIPS CPU saves EPC and Cause is on MIPS exceptions; why to use interrupts instead of polling is on embedded I/O.
The vector table
At address 0x0000 the chip keeps the vector table, one entry per source. Entry 0x0000 is reset: after power-on the CPU starts there, and it leads to main. The page's other entries are TIMER at 0x0002, BUTTON at 0x0004 and UART at 0x0006. Each holds the address of that source's ISR. On the 8051 and on AVR chips each entry is a short jump instruction. On ARM Cortex-M each entry is a plain address, and the very first word is the initial stack pointer, loaded before the reset handler runs (see Cortex-M exceptions).
What taking an interrupt costs
The source sets its pending flag. The CPU only looks at the flags between instructions, so it first finishes the current one. Then the hardware does the entry: it pushes the return address PC and the status register SR (with the global enable bit I and the current level L) on the stack, reads the vector and jumps. Here that is 6 cycles. The ISR's first instructions (its prologue) save the registers it will use; here PUSH R0. At the end, POP R0 and RETI undo it all: RETI pops SR and PC in 4 cycles. The interrupt latency is the time from the request to the ISR's first instruction.
Demo: one interrupt, step by step: the button rises at cycle 5, in the middle of a 2-cycle JMP. The CPU sees it at cycle 6, the entry takes cycles 6–11 and BUTTON_ISR starts at cycle 12. Latency = 12 − 5 = 7 cycles (1 to finish the JMP + 6 for the entry). The whole round trip, entry to RETI, is 19 cycles, of which only 5 do the work (presses++).
Priority: preempt or wait
The rule is one comparison. A pending source is taken only if its priority is strictly more urgent than the level the CPU runs at. Three cases follow:
| request vs running level | what happens | demo, latency |
|---|---|---|
| more urgent | preempts at the next instruction boundary: a second frame on the stack | a more urgent interrupt nests: UART (0) cuts into TIMER (1), 7 cycles |
| less urgent | pending until the running ISR returns | a less urgent one waits: BUTTON (2) waits for TIMER, 21 cycles |
| equal | pending too: equal priority never preempts | equal priority, same cycle: UART set to 1, 30 cycles |
When two pending sources have the same priority, the chip needs a tie-break. Here, as on most chips, the lower vector address wins. In Demo: equal priority, same cycle TIMER and UART both ask at cycle 4 with priority 1. TIMER (0x0002) goes first, its entry starts at cycle 4, so its latency is 6. UART waits for the whole TIMER round trip (24 cycles) plus its own entry: 30 cycles. Priority is how you choose which source pays for the others.
Nesting and the stack
Every level that is cut into leaves one frame on the stack: PC, SR and R0, 3 words here. In Demo: three levels deep the button comes at cycle 2, the timer at 10 and the UART at 22. Each one is more urgent than the one running, so each cuts in. At the deepest point the stack holds 9 words (18 bytes) and SP has gone from 0x0800 down to 0x07EE. The handlers start BUTTON → TIMER → UART and finish in the opposite order, UART → TIMER → BUTTON, each one picking up exactly where it was cut. Look at the TIMER frame: its saved R0 is 1, the half-done ticks + 1 that TIMER_ISR had computed but not yet stored. The latencies are 7, 7 and 6 cycles: nesting keeps the urgent source fast.
So the worst-case stack need is the sum of one frame per priority level, plus what each ISR's own code uses. Fewer levels means less stack. An ISR of the same level can never nest in itself, which is why the page's three sources with three different levels give at most 3 frames.
Back-to-back interrupts
In Demo: a less urgent one waits BUTTON is still pending when TIMER_ISR ends at cycle 27. The CPU pops PC and SR (4 cycles), finds that the button now beats main, and pushes the very same PC and SR again (6 cycles). Those 10 cycles do nothing useful. ARM Cortex-M chips skip that pair with tail-chaining (Cortex-M exceptions). Many small chips also run at least one instruction of the interrupted code before taking the next interrupt.
A variable shared with an ISR
The stack saves registers, not memory. If main and an ISR both change the same variable, the ISR can run between main's read and main's write. count-- compiles to three instructions: LD R0,[count], SUB R0,#1, ST [count],R0. In Demo: shared counter, a lost update count starts at 3. main loads 3 into R0, the UART comes in at cycle 1, UART_ISR saves R0, adds 1 and stores count = 4, then restores R0 = 3 and returns. main subtracts and stores 2. The answer should be 3 − 1 + 1 = 3: the UART's byte is lost. This is the race condition of threads, on a single core and with no OS at all.
Two things are needed to fix it:
volatile uint8_t count;tells the compiler that the variable can change behind its back. It must load it from memory every time and store it every time. Without it, an optimizing compiler may keepcountin a register across a loop, and main would never see the ISR's updates, for example inwhile (count == 0) { }. Butvolatiledoes not makecount--one step: the demo's count is volatile and still loses the update.- A critical section: turn interrupts off around the read-modify-write,
cli(); count--; sei();on AVR. In Demo: fix with volatile + cli/sei the UART asks at cycle 2, while I = 0. Its flag stays set, the request is not lost. It is taken right afterseiat cycle 7, and count ends at 3 ✓. The latency grows from 7 to 11 cycles, the length of the protected code. Keep critical sections a few instructions long.
Other fixes: disable only that one source (its enable bit) instead of all of them, raise the CPU level to the ISR's level for a moment, use an instruction that changes memory in one step if the chip has one, or let only one side write (the ISR writes a head index, main writes a tail index, as in a ring buffer).
On real chips
| chip family | levels | what the hardware saves | nesting |
|---|---|---|---|
| 8051 | 2 (IP register), 4 on newer ones | PC only; the ISR pushes PSW and registers | a high-level source can cut into a low-level ISR |
| AVR (ATmega) | fixed order by vector number | PC only; I is cleared on entry, the ISR saves SREG | none unless the ISR runs sei itself |
| ARM Cortex-M | up to 256 (NVIC) | R0–R3, R12, LR, PC, xPSR, 12 cycles | by priority, with tail-chaining |
The page's chip is a mix: 8051-style levels, with the hardware saving PC and SR. When the ISRs are periodic jobs, the same numbers feed a schedulability check; see rate-monotonic analysis and, for a design with only one interrupt, a time-triggered scheduler.
See also the button debounce state machine, a short 10 ms task that replaces an edge interrupt on a bouncing pin.
See also embedded software architectures, where ISRs set flags, fill queues or wake RTOS tasks, and the response of the task code depends on which design is used.
See also a FIR filter accelerator, where the CPU sleeps in WFI until the accelerator's done interrupt and the handler clears DONE.
See also MCU startup from power-on to main() for what a microcontroller does before main runs and its interrupts are enabled.
See also the watchdog timer, where a timer interrupt that keeps running while the main loop is stuck hides the hang from the watchdog.
What the page leaves out
One register and one RAM bank; real ISRs save more registers, and compilers decide which. Instruction times are fixed; real latency also depends on wait states, flash fetch, caches and the longest instruction (a multiply or a block copy). No peripheral timing: the flag is set at the given cycle. Level-triggered lines that stay asserted, clearing a flag in software, priority grouping and sub-priorities, the NMI and fault handlers, and Cortex-M's late arrival are not shown. Interrupts on a multi-core chip or under an RTOS are a separate topic.
On the mind map
References
Microchip, ATmega328P datasheet: Reset and interrupt handling, interrupt vectors
avr-libc manual: <avr/interrupt.h>, ISR, cli and sei, nested interrupts
Arm, Cortex-M3 Devices Generic User Guide: exception model, entry and return
Nigel Jones, Introduction to the volatile keyword (Embedded.com)