The idea: one CPU, four devices, four program shapes
A small microcontroller often has to serve several devices at once: bytes arrive on a UART, a user presses a button, a sensor must be read every 10 ms, a display must be redrawn now and then. There is one CPU, so the program needs a plan for who runs when. David E. Simon's An Embedded Software Primer sorts these plans into four architectures, from the simplest to the most powerful: round-robin, round-robin with interrupts, function-queue scheduling and a real-time operating system (RTOS). The page builds the same device all four ways and feeds each one exactly the same events. Then it measures the response time of every event: from the moment it happens to the moment its handler has finished.
The device and its events
Each kind of event has a handler: the task code that does the real work. Interrupt service routines (ISRs) and task switches take a few microseconds, so the page counts them as 0 ms and draws them as red ticks.
| event | handler | time | priority |
|---|---|---|---|
| a byte on the UART | UART_Handler (parse the byte) | 1 ms | 1 (most urgent) |
| a button edge | Button_Handler | 2 ms | 2 |
| sensor timer, every 10 ms | Sensor_Read | 3 ms | 3 |
| display timer, every 50 ms | Display_Update | 8 ms (20 ms in the slow trace) | 4 (least urgent) |
The standard trace has the sensor timer at 0, 10, …, 60 ms, the display timer at 0 and 50 ms, the button at 0 and 33 ms and UART bytes at 1, 24 and 54 ms. The UART is the device that matters most: if its handler is slow, the other side of the link waits, and bytes can be lost.
Round-robin: a super loop that polls
while (1) {
if (uart_rx_ready()) UART_Handler();
if (button_pressed()) Button_Handler();
if (sensor_timer_flag()) Sensor_Read();
if (display_timer_flag()) Display_Update();
}
There are no interrupts. The loop asks each device in turn whether it needs service, reading a status bit in a hardware register. It is the simplest program there is, and it has no shared-data problems, because only one piece of code ever runs. But a device is seen only when the loop reaches its check. In the worst case an event comes just after its check and waits for every other handler: here 2 + 3 + 8 = 13 ms, plus its own 1 ms. In the standard trace the byte at 1 ms comes just after the loop checked the UART at 0 ms, then waits while Button_Handler, Sensor_Read and Display_Update run from 0 to 13 ms: response 13 ms (Demo: round-robin super loop: UART 13, button 2, sensor 12, display 13 ms). Adding a handler makes every other one slower, so the timing changes every time the code changes.
Polling can also lose data. A UART receive register holds one byte. When the next byte arrives before the loop has read the first, the hardware sets an overrun error (ORE on an STM32) and the new byte is gone (Demo: a UART burst, polling loses bytes: the bytes at 6, 7 and 8 ms all arrive while the byte from 1 ms still waits, and all three are lost).
Round-robin with interrupts
volatile bool fButton, fSensor, fDisplay;
void USART1_IRQHandler(void) { rx_buf[rx_head++ % N] = USART1->DR; }
void EXTI0_IRQHandler(void) { fButton = true; }
...
while (1) {
while (rx_head != rx_tail) UART_Handler(); /* one byte each */
if (fButton) { fButton = false; Button_Handler(); }
if (fSensor) { fSensor = false; Sensor_Read(); }
if (fDisplay) { fDisplay = false; Display_Update(); }
}
Each device now has an ISR that does the urgent part at once: the UART ISR copies the byte out of the register into a ring buffer, and the others set a flag. Many people call this foreground/background: ISRs in the foreground, the loop in the background. The ISRs have hardware priorities among themselves, and no byte is lost any more (Demo: a UART burst: the bytes at 6, 7 and 8 ms are saved and handled from 14 to 17 ms, each 9 ms after it came). But the handlers still run in the loop's fixed order, so their response is exactly as bad as with polling (Demo: round-robin with interrupts: the same 13, 2, 12, 13 ms). The price is shared data: the ISR and the loop both touch the flags and the buffer, so they must be volatile, and code that reads and clears them must disable interrupts for a moment. A bool flag also merges two events into one: with a 20 ms display redraw, the sensor ticks at 20 and 60 ms find fSensor still set, and those two samples are lost (Demo: a 20 ms display redraw). A counter instead of a bool would keep them.
Function-queue scheduling
void USART1_IRQHandler(void) { save_byte(); queue_put(UART_Handler, 1); }
void TIM2_IRQHandler(void) { queue_put(Sensor_Read, 3); }
...
while (1) {
void (*f)(void) = queue_get_highest(); /* waits while the queue is empty */
f();
}
Now the ISRs do not set flags: each one puts a pointer to its handler into a queue sorted by priority, and the loop always calls the most urgent entry next. The UART no longer waits behind every handler, only behind the one that is already running, because a handler still runs to its end. So its worst case is the longest handler plus its own time: 8 + 1 = 9 ms. In the standard trace the byte at 1 ms is handled at 2 ms, right after Button_Handler, but the byte at 54 ms comes 1 ms after Display_Update started and waits until 61 ms: 8 ms (Demo: function-queue scheduling: UART 8, button 2, sensor 7, display 14 ms). Every ISR queues an entry, so nothing is lost. The weak spot is the longest handler: make Display_Update take 20 ms and the UART worst case grows to 20 ms (Demo: a 20 ms display redraw). Low-priority entries can also wait for a long time if urgent ones keep coming.
An RTOS with priorities
void USART1_IRQHandler(void) { save_byte(); xSemaphoreGiveFromISR(uartSem, &woken); portYIELD_FROM_ISR(woken); }
void UartTask(void *p) { /* priority 4, the highest of the four */
for (;;) { xSemaphoreTake(uartSem, portMAX_DELAY); UART_Handler(); }
}
/* ButtonTask, SensorTask, DisplayTask the same, with priorities 3, 2, 1 */
Each handler becomes a task with its own stack and a priority. A task waits on a semaphore; the ISR gives it, and the RTOS kernel switches at once to the highest-priority task that is ready, even if a lower one is in the middle of its work. That is preemption. The UART task never waits for another handler: every byte is done 1 ms after it arrives, in every trace (Demo: RTOS with priorities). The button task is preempted by the byte at 1 ms (3 ms instead of 2). The cost lands on the least urgent task: Display_Update is interrupted by sensor reads and bytes and its worst case grows to 17 ms (20 ms in the burst, 38 ms with the 20 ms redraw). A new low-priority task does not change the response of the high-priority ones, which makes an RTOS the most stable design when the code grows. FreeRTOS numbers its priorities upwards (a bigger number is more urgent); the page's "priority 1" is the most urgent.
The rest of the cost is in the code. The kernel takes flash (FreeRTOS says about 6–12 KB on a typical port), each task needs its own stack in RAM, and any data that two tasks share must be protected with a mutex, because a task can now be stopped between any two instructions. With a mutex comes priority inversion; see priority ceiling and SRP and real-time scheduling and priority inversion. Whether every task meets its deadline can be checked on paper with rate-monotonic analysis, or with earliest-deadline-first priorities.
Worst-case response, side by side
| trace | round-robin | with interrupts | function queue | RTOS |
|---|---|---|---|---|
| standard | 13 ms, 0 lost | 13 ms, 0 lost | 8 ms | 1 ms |
| UART burst | 13 ms, 3 bytes lost ✗ | 13 ms, 0 lost | 8 ms | 1 ms |
| 20 ms display | 25 ms, 3 lost ✗ | 25 ms, 2 sensor ticks lost ✗ | 20 ms | 1 ms |
Choosing one
Simon's advice is to pick the simplest architecture that meets the response requirements. Many products are a round-robin loop with a few ISRs; an RTOS pays off when there are many tasks with different deadlines, or when the program will keep growing.
| architecture | priorities | worst response of task code | when code changes | code cost |
|---|---|---|---|---|
| round-robin | none | sum of all handlers | every handler slows the others | smallest: one loop, no ISRs |
| round-robin with interrupts | ISRs by hardware priority; handlers none | sum of all handlers (plus ISR time) | good for ISRs, poor for handlers | + ISRs and data shared with them |
| function queue | ISRs, then handlers by priority | longest handler (plus ISR time) | fairly good | + a priority queue of function pointers |
| RTOS | ISRs, then tasks by priority, with preemption | ISR time + task switch | very good | + kernel (a few KB), a stack per task, mutexes |
See also a time-triggered co-operative scheduler, a round-robin with one timer interrupt that flags tasks from a table, and the cyclic executive, which fixes at design time what runs in every frame.
See also interrupt priorities and nesting for what happens inside the "0 ms" ISR ticks of this page, and button debounce as a state machine for a button handler that a super loop can call every 10 ms.
See also preemptive vs cooperative scheduling on a general-purpose OS, the game loop and its fixed timestep, a super loop of another kind, and the watchdog timer that resets a loop that has hung.
See also MCU startup from power-on to main() for the startup code that runs before the super loop or RTOS starts.
What the page leaves out
ISRs, the polling checks and task switches take 0 ms here; on a real chip each costs microseconds, and Simon's bounds add the time of all ISRs to every task's response. Handler times are fixed; real ones depend on the input, so the worst-case execution time must be measured. The page does not show interrupt latency and nesting, disabling interrupts around shared data (which delays the ISRs), a full ring buffer, an RTOS's tick interrupt, time slicing between equal priorities, mutexes and priority inheritance, stack sizing, or low-power sleep in the idle loop. The traces are short and chosen by hand; a real worst case must be found by analysis, not by one test run.