Interrupts & Real-Time
Microcontroller Programming · Embedded Systems & Firmware track
7 min read
In this module
Responding to Events
In bare-metal code, the CPU sits in a main loop. Trouble is, peripherals don't politely wait their turn. A UART receives a byte. A timer expires. Someone presses a button. Interrupts let the CPU drop whatever it was doing, run a handler, and resume right where it left off.
Interrupt Vectors and ISRs
The interrupt vector table is an array of function pointers parked at the start of flash memory, one entry per interrupt source. When an interrupt fires, the hardware:
- Pushes the current register state onto the stack (automatically on Cortex-M)
- Reads the handler address from the vector table
- Jumps to the handler (Interrupt Service Routine - ISR)
- When the ISR returns, pops the saved registers and resumes the interrupted code
// Vector table (partial) for ARM Cortex-M__attribute__((section(".isr_vector")))void (*const vector_table[])(void) = { (void (*)(void))(&_estack), // Initial stack pointer Reset_Handler, // Reset NMI_Handler, // Non-maskable interrupt HardFault_Handler, // Hard fault // ... more exception handlers ... TIM3_IRQHandler, // Timer 3 interrupt USART2_IRQHandler, // UART 2 interrupt // ... more peripheral interrupts ...};
// ISR for UART receivevoid USART2_IRQHandler(void) { if (USART2->SR & USART_SR_RXNE) { char c = USART2->DR; // Read received byte (also clears interrupt flag) if (rx_index < sizeof(rx_buffer)) // without this, a long burst overruns the buffer rx_buffer[rx_index++] = c; }}On Cortex-M the hardware does all of the saving and restoring itself, which is why an ISR can be an ordinary C function:
The magic in LR (0xFFFFFFF9 for a return to thread mode on the main stack) is what tells the hardware that this BX LR is an exception return and not an ordinary one. If another interrupt is pending when the handler finishes, the core skips the pop and re-push and goes straight to the next handler. That's tail-chaining.
ISR Design Rules
ISRs preempt everything else, so they live by strict rules:
Keep them short. Do the bare minimum — read data, set a flag, update a buffer — and get out. A long ISR holds up every other interrupt and the main loop with it.
No blocking. Never call anything that waits inside an ISR. No delay loops, no printf, no malloc.
Use volatile for shared data. Variables touched by both the ISR and the main loop need volatile so the compiler doesn't cache stale copies in registers.
Mind atomicity. Reading or writing shared data wider than one bus access (32 bits on Cortex-M) isn't atomic. Disable interrupts briefly around any multi-step operation on shared data.
volatile uint32_t tick_count = 0; // Shared between ISR and main
void SysTick_Handler(void) { tick_count++; // LDR, ADD, STR: safe only because nothing else writes it}
void main(void) { uint32_t last = 0; while(1) { uint32_t now = tick_count; // one 32-bit read is atomic if (now - last >= 1000) { // unsigned maths copes with wrap-around // 1 second has passed last += 1000; toggle_led(); } }}An aligned 32-bit load or store is atomic on Cortex-M, but tick_count++ is a read-modify-write of three instructions. A version where main resets tick_count = 0 after its check loses any tick that lands between main's comparison and its store. Keeping a single writer (the ISR) and taking a snapshot in main avoids the race. If both sides really must modify the variable, wrap main's update in __disable_irq()/__enable_irq() or use LDREX/STREX.
A high-priority task needs a mutex that a low-priority task holds, so it blocks. A medium-priority task, which wants nothing to do with that mutex, now preempts the low-priority one, and the high-priority task waits for as long as the medium one runs. This is priority inversion and can cause missed deadlines. An ISR can't be caught this way, since it preempts every task, and it must never block on a mutex in the first place. RTOSes solve the task case with priority inheritance (temporarily raising the low-priority task's priority).
The textbook case involves three tasks and a mutex. Follow the high-priority task: it ends up waiting on a medium-priority task it shares nothing with.
With priority inheritance, L runs at H's priority for as long as it holds the mutex, so M can't get in between. This is roughly what happened to the Mars Pathfinder lander in 1997, which kept resetting until engineers enabled inheritance on the offending VxWorks mutex.
Priority Levels
ARM Cortex-M lets you configure interrupt priorities. When multiple interrupts queue up, the highest-priority one wins. A higher-priority interrupt can also barge into a running lower-priority ISR mid-execution — that's nested interrupts.
The NVIC (Nested Vectored Interrupt Controller) manages priorities:
// Set UART interrupt to priority 2 (lower number = higher priority)NVIC_SetPriority(USART2_IRQn, 2);NVIC_EnableIRQ(USART2_IRQn);
// Set Timer interrupt to priority 1 (higher priority than UART)NVIC_SetPriority(TIM3_IRQn, 1);NVIC_EnableIRQ(TIM3_IRQn);Priority assignment is a load-bearing design decision. Time-critical interrupts (motor control, safety systems) take the top slot. Communication interrupts settle in below them. Background processing runs in the main loop at the bottom of the priority pile.
RTOS Concepts
Once your bare-metal main loop starts juggling several tasks with different timing requirements, it stops scaling. A Real-Time Operating System brings in structured concurrency.
Tasks (threads): independent functions that run concurrently. The RTOS scheduler decides who runs next based on priority and time slices.
FreeRTOS basics:
// Create two tasks with different prioritiesxTaskCreate(sensor_task, "Sensor", 256, NULL, 2, NULL); // FreeRTOS: higher number = higher priority, // the opposite of NVIC numberingxTaskCreate(display_task, "Display", 512, NULL, 1, NULL);
// Start the schedulervTaskStartScheduler();
// sensor_task: reads sensors every 10ms (high priority)void sensor_task(void *params) { while(1) { read_sensors(); vTaskDelay(pdMS_TO_TICKS(10)); // Yield for 10ms }}
// display_task: updates display every 100ms (low priority)void display_task(void *params) { while(1) { update_display(); vTaskDelay(pdMS_TO_TICKS(100)); }}Synchronisation primitives: Mutexes protect shared resources. Semaphores signal events between tasks. Queues pass data between tasks safely.
Timing Constraints
Real-time systems live or die by deadlines. A hard real-time system fails outright when a deadline slips — think pacemaker. A soft real-time system degrades gracefully, like a media player dropping a frame and carrying on.
Meeting timing constraints means:
- Knowing the worst-case execution time (WCET) of every ISR and task
- Keeping interrupt latency (signal-to-ISR-start) inside known bounds
- Designing away priority inversion and unbounded blocking
- Stress-testing under worst-case conditions: maximum interrupt rate, maximum throughput
In real-time systems, average performance does not matter - worst-case performance does. A system that processes sensor data in 1 microsecond on average but occasionally takes 10 milliseconds will miss deadlines. Real-time analysis focuses on guaranteed upper bounds, not averages. This is fundamentally different from desktop application performance optimisation.