Firmware architectures
Superloop, interrupts, event-driven or an RTOS: how to structure firmware and when to choose each.
Four ways to structure firmware
Every firmware answers one question: what runs next, and when? There are four common answers, and most products use one of them or a mix. Choosing well early saves a rewrite later.
| Architecture | What decides what runs | Good for | Breaks down when |
|---|---|---|---|
| Superloop | A fixed order in while (1) | Small, simple devices | One job is slow or must react quickly |
| Superloop + interrupts | Hardware events interrupt the loop | Most small products | ISRs grow, or many events need sharing |
| Event-driven (event queue) | Events queued and dispatched one at a time | UI devices, protocols, low power | Long jobs block every other event |
| RTOS | A scheduler, by priority | Several independent timing requirements | RAM is tiny, or the team has no RTOS experience |
1. The superloop
int main(void) {
init_hardware();
while (1) {
read_sensors();
update_control();
update_display();
handle_buttons();
}
}
Simple, predictable and easy to debug: everything runs in a known order. Its weakness is latency: a button press waits until handle_buttons() comes round again, so the worst-case reaction time is the time of one whole loop. If update_display() takes 50 ms, every other job can be 50 ms late.
The fix within a superloop is to make every job short and non-blocking: no delay(), no waiting on a peripheral. Long work is split into steps, usually with a state machine, so each call does a little and returns.
2. Superloop with interrupts
Interrupts handle what cannot wait: a byte arriving on a UART, a timer tick, an edge on a pin. The rule is to keep ISRs short: capture the data, set a flag or put it in a buffer, and let the loop do the rest.
#include <stdio.h>
#include <stdbool.h>
/* Shared between the "ISR" and the loop: volatile, and each written by one side only. */
static volatile bool tick_flag = false;
static volatile unsigned ticks = 0;
/* What the timer interrupt would do: the minimum, then return. */
static void timer_isr(void) {
ticks++;
tick_flag = true;
}
int main(void) {
unsigned blinks = 0;
for (int t = 0; t < 10; t++) { /* the superloop; here 10 passes stand for time going by */
if (t % 3 == 0) timer_isr(); /* in real firmware the hardware calls it */
if (tick_flag) { /* the loop does the work the ISR asked for */
tick_flag = false;
blinks++;
printf("pass %d: tick %u handled, LED toggled\n", t, ticks);
}
}
printf("%u ticks, %u handled\n", ticks, blinks);
return 0;
}
This is how most small products are built. It stops scaling when there are many flags, and the loop becomes a long chain of if (flag) checks whose order is an accidental priority scheme.
3. Event-driven
Instead of flags, interrupts and timers post events into a queue, and the main loop takes one event at a time and dispatches it to whatever handles it. When the queue is empty, the CPU can sleep until the next interrupt: ideal for battery devices.
#include <stdio.h>
typedef enum { EV_BUTTON, EV_TIMER, EV_UART_LINE } event_t;
#define QSIZE 8
static event_t queue[QSIZE];
static unsigned head = 0, tail = 0;
static int post(event_t e) { /* called from ISRs */
if ((head + 1) % QSIZE == tail) return 0; /* full: the event is lost, so count it in real code */
queue[head] = e;
head = (head + 1) % QSIZE;
return 1;
}
static int next_event(event_t *e) { /* called from the main loop */
if (tail == head) return 0;
*e = queue[tail];
tail = (tail + 1) % QSIZE;
return 1;
}
static void dispatch(event_t e) {
switch (e) {
case EV_BUTTON: printf("button: change mode\n"); break;
case EV_TIMER: printf("timer: sample the sensor\n"); break;
case EV_UART_LINE: printf("uart: run the command\n"); break;
}
}
int main(void) {
post(EV_TIMER); post(EV_BUTTON); post(EV_UART_LINE); post(EV_TIMER); /* as the ISRs would */
event_t e;
while (next_event(&e)) dispatch(e);
printf("queue empty: sleep until the next interrupt\n");
return 0;
}
Each handler must run to completion quickly: while one runs, no other event is handled. Combined with state machines (each handler is a transition), this is the "active object" pattern used by frameworks such as QP.
4. An RTOS
With an RTOS, each job is a task with its own loop, stack and priority, and a scheduler preempts lower-priority tasks when higher ones become ready. A slow task no longer delays an urgent one: the motor control loop at high priority keeps its timing while the display task takes as long as it needs.
The costs are real: RAM for a stack per task, new bug classes (races, deadlocks, priority inversion, stack overflow), and more to learn. See the RTOS lessons, and the simulator's RTOS projects to watch a scheduler run.
How to choose
Ask three questions:
- What is the tightest reaction time, and what is the slowest job? If the slowest job takes longer than the tightest deadline, a superloop cannot work without splitting the job: consider an RTOS.
- How many independent timing requirements are there? One or two: a superloop with interrupts. Several unrelated ones (motor control, a radio stack, a UI): an RTOS.
- What are the power and RAM budgets? Event-driven code sleeps naturally and needs one stack. An RTOS needs a stack per task, though its idle hook can sleep too.
Pitfall: Moving to an RTOS does not make slow code fast. A task that busy-waits still burns the CPU, and at high priority it starves every task below it.
Interview question: When would you choose an RTOS over a superloop?
Answer: When there are several independent timing requirements that a single loop cannot meet together: for example a control loop that must run every millisecond while a display or radio stack does long operations. An RTOS lets each run as its own task, with priorities deciding which runs first. I would stay with a superloop and interrupts for simple devices, very tight RAM, or certification constraints, and make every job non-blocking with state machines.
Build it: a main loop that never blocks
This is step 3 of the module project. The thermostat has no RTOS: one main loop reads the sensor, runs the heating control and answers the buttons. Any delay() in it would freeze the buttons, so each job runs when its time has come, measured on a millisecond counter. That counter wraps around after 49.7 days, and thermostats run for years.
Lab: Non-blocking timing and hysteresis control
due(last, now, period)decides whether a job is due: true when at leastperiodms have passed since*last, and then it moves*laston by exactlyperiod(not tonow, so the job does not drift later and later). It must work when the 32-bit millisecond counter wraps from0xFFFFFFFFto 0: compute the elapsed time asnow - *lastin unsigned arithmetic, never comparenowwith a deadline directly.heater_update(temp, target)is the heating control, run every second. It keeps the heater state and returns it. To stop the relay clicking on and off around the target, it uses hysteresis of 0.5 °C: switch on belowtarget - 50and off abovetarget + 50(hundredths of a degree); in between, keep the current state. The heater starts off.
Going deeper
Interview question: Would you use a superloop or an RTOS for a smart greenhouse controller, and why?
Answer: A superloop with non-blocking tasks is enough while every job is short and timing is loose: sensors once a second, a menu, a console. Choose an RTOS once jobs with different deadlines must preempt each other, a blocking stack such as Wi-Fi or TLS is added, or the team grows, and accept its costs (stacks, synchronisation, analysis).
Interview question: What problems can moving from a superloop to an RTOS introduce?
Answer: Race conditions on data shared between tasks, which need mutexes, queues or critical sections; deadlocks and priority inversion; stack overflows, since each task has its own fixed stack; nondeterminism that makes bugs harder to reproduce; and more RAM and flash used by the kernel and stacks. The design also needs priorities assigned deliberately, for example by deadline (rate-monotonic), rather than by how important a task feels.
Interview question: How does an event-driven design save power?
Answer: All work is triggered by events posted from interrupts, so when the event queue is empty there is nothing to do and the main loop can put the CPU to sleep until the next interrupt. There is no polling loop spinning to check flags, so the CPU spends most of its time asleep. The same applies to an RTOS through its idle task, which can enter sleep or use tickless idle.
Explain it: In your own words, compare a superloop, an event-driven design and an RTOS.
Answer: A superloop calls every job in a fixed order forever; it is simple and predictable, but every job waits for all the others, so one slow job delays everything. An event-driven design queues events from interrupts and timers and handles them one at a time; the CPU sleeps when the queue is empty, but each handler must be short because nothing else runs meanwhile. An RTOS gives each job its own task with a priority and preempts lower-priority tasks, so urgent work meets its deadline even while slow work runs, at the cost of RAM for stacks and new problems like races and deadlocks.