Skip to content
systemcoding.dev
RTOS

Superloop vs RTOS: When Bare-Metal Firmware Stops Scaling

A superloop is fine until timing, blocking calls and feature count collide. See the signs that bare-metal firmware needs an RTOS and when it still does not.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the Arm, C and Linux logos.

Most firmware starts life as a superloop: initialize the hardware, then while (1) forever, calling one function after another. It is the right first architecture, and plenty of shipping products never leave it. The trouble arrives quietly. One feature adds a 40 ms flash write, another adds a display refresh, and suddenly the button that used to respond instantly feels sticky. This post compares the two architectures on the axes that matter, shows the exact moment a superloop breaks, and gives a decision table. The cornerstone guide on real-time operating systems for microcontrollers places this choice inside the larger design.

What a superloop is

A superloop, also called a main loop or foreground/background system, runs everything from one thread of execution. Interrupt handlers (the background) set flags or fill buffers, and the loop (the foreground) polls those flags and does the real work.

superloop.cc
#include <stdbool.h>
#include <stdint.h>

extern volatile bool g_button_pressed;
extern volatile bool g_uart_line_ready;

void led_toggle(void);
void handle_line(void);
void read_temperature(void);
void update_display(void);

int main(void)
{
    board_init();

    for (;;)
    {
        if (g_button_pressed)
        {
            g_button_pressed = false;
            led_toggle();
        }
        if (g_uart_line_ready)
        {
            g_uart_line_ready = false;
            handle_line();
        }
        read_temperature();
        update_display();
    }
}

Every function must return quickly, because nothing else runs while it works. That single rule is the whole architecture, and it is also the whole problem.

Where the loop breaks

Suppose update_display() takes 30 ms to push a frame over SPI, and read_temperature() blocks for 12 ms on an ADC conversion. The longest path through one iteration is the sum of everything, so the button is serviced at most once every 42 ms plus whatever handle_line() costs. The response time of every feature is now the loop time, and it grows each time anyone adds code.

The usual fix is a state machine per feature: split update_display() into 30 slices of 1 ms each, remember where you were, and resume on the next pass. That works. It also turns straight-line code into a tangle of switch statements, and each slice boundary is a place for a bug.

display_state.cc
typedef enum { DISP_IDLE, DISP_SEND_HEADER, DISP_SEND_ROWS, DISP_DONE } disp_state_t;

static disp_state_t s_state = DISP_IDLE;
static uint8_t s_row;

void update_display(void)
{
    switch (s_state)
    {
    case DISP_IDLE:
        s_state = DISP_SEND_HEADER;
        break;
    case DISP_SEND_HEADER:
        spi_send_header();
        s_row = 0;
        s_state = DISP_SEND_ROWS;
        break;
    case DISP_SEND_ROWS:
        spi_send_row(s_row++);
        if (s_row == 32) { s_state = DISP_DONE; }
        break;
    case DISP_DONE:
        s_state = DISP_IDLE;
        break;
    }
}

Each call now does one small step, so the loop stays fast. Multiply this by ten features and you maintain ten hand-written schedulers.

What an RTOS changes

With FreeRTOS Kernel V11.3.3, the same display code goes back to straight-line form, because blocking in one task does not stop the others:

display_task.cc
#include "FreeRTOS.h"
#include "task.h"

static void vDisplayTask(void *pvParameters)
{
    (void) pvParameters;

    for (;;)
    {
        spi_send_header();
        for (uint8_t row = 0; row < 32; row++)
        {
            spi_send_row(row);
        }
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

The kernel preempts this task when a higher-priority task, such as the button handler, becomes ready. The scheduler is the state machine you would have written by hand, written once, tested widely and maintained by someone else.

PropertySuperloopRTOS
Worst-case response of a featureSum of every function in the loopOwn execution time plus higher-priority work
Adding a featureCan slow every other featureIsolated unless it shares a resource
Blocking callsForbidden or hand-slicedNormal, the kernel runs other tasks meanwhile
Code structureOne loop, many state machinesOne task per activity
RAM costOne stackOne stack and one control block per task
Flash costNoneKernel code, typically a few kilobytes
DebuggingSingle thread of controlConcurrency bugs: races, deadlocks, priority inversion

The signs that it is time

You do not need a formula. These symptoms, appearing together, mean the superloop is costing more than an RTOS would.

  1. A feature misses its deadline only when another feature runs, and you cannot say which one.

  2. You have written more than two or three hand-rolled state machines purely to avoid blocking.

  3. Timing requirements span orders of magnitude: a 100 microsecond control loop beside a 2 second network retry.

  4. Power matters, and the loop spins when it could sleep. A kernel's idle task is where you hook low-power entry, and the tickless idle option reduces tick wakeups further.

  5. More than one engineer works on the firmware and the loop has become a merge-conflict hotspot.

When the superloop is still right

An RTOS is not a free upgrade, and we think it is the wrong tool in some cases.

A device with one or two interrupt-driven jobs and a few milliseconds of slack gets nothing from a scheduler. The 8-bit sensor node that wakes on a timer, reads one value, transmits and sleeps is simpler and smaller without one. Certification can also argue against it: a loop with fixed, analyzable timing is easier to put through a safety review than a preemptive system with dynamic interactions. And RAM is the hard limit on parts with 2 KB: each FreeRTOS task needs its own stack plus a task control block, so ten tasks can consume the whole memory.

The middle path matters too. A cooperative scheduler or an event-driven design can keep the single-stack simplicity while removing the sliced state machines. Those options each get their own post later in this series.

Working out the response time on paper

Before choosing, do the arithmetic for your own loop. List every call in one iteration with its worst-case duration, and add them. Say read_temperature() costs 12 ms, update_display() costs 30 ms, handle_line() costs 3 ms in the worst case, and the button work costs 1 ms. One full pass is 46 ms, so a button press that arrives just after the loop checked the flag waits up to 46 ms before anything happens, plus the 1 ms of work itself. If the requirement says 20 ms, no amount of tuning inside one function will fix it, because the problem is the sum.

Under an RTOS the same button work sits in a high-priority task. Its worst-case response is the time to get from the interrupt to that task, which is the interrupt handler, one context switch and the longest stretch the kernel keeps interrupts masked, plus its own 1 ms. The 30 ms display transfer no longer appears in the budget at all, because the display task runs at a lower priority and gets preempted. That is the whole argument in one paragraph: the superloop's latency is a sum over the system, and the RTOS's latency is a sum over the things that outrank you.

The same arithmetic shows when you do not need the switch. If the sum is 3 ms and the tightest deadline is 50 ms, you have a 16-fold margin and every added feature can be checked by adding one more line to your list. Keep the list in the repository next to the code and update it whenever the loop changes; a superloop with a current timing budget is a perfectly respectable design.

Moving over without a rewrite

Do not convert everything at once. Start with the feature that hurts, give it a task, and leave the rest in a single "legacy" task that runs the old loop at low priority. The interrupts keep their flags, the old code keeps working, and the new task gets real preemption. Over a few releases, the legacy task shrinks.

Shared flags that were safe in a superloop become races under preemption. A volatile bool set by an interrupt and read by one loop is fine. The same variable read and modified by two tasks needs a queue, a notification or a critical section.

Also inEmbedded
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.