Skip to content
systemcoding.dev
RTOS

The Complete Guide to Real-Time Operating Systems for Microcontrollers

How an RTOS works on a microcontroller: tasks, scheduling, interrupts, queues, mutexes, memory and timing, with FreeRTOS code and a route through the series.

25 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arm, C and STMicroelectronics logos.

A real-time operating system, or RTOS, is a small kernel that lets a microcontroller run several independent activities as if each had the processor to itself, while guaranteeing that the most urgent one gets the CPU within a bounded time. If you have written firmware as a while (1) loop and watched it grow until one slow function made the buttons feel sticky, an RTOS is what you reach for next. This guide explains how it works from the first principle to the production checklist. It covers tasks and the scheduler, what real-time actually promises, interrupts, communication between tasks, locking, memory, timing and debugging, with FreeRTOS Kernel V11.3.3 code on a Cortex-M4F for every idea. It also tells you honestly when not to use one. Each section is a self-contained answer, and the later posts in this series go deeper on the topics named along the way.

The answer in one paragraph

An RTOS gives a microcontroller three things a main loop cannot: concurrency (several tasks, each written as straight-line code), priorities (the most urgent ready task always runs) and blocking (a task can wait for an event without wasting CPU). The kernel does it with a tick timer, a scheduler and a context switch that saves one task's registers and restores another's. In return you pay a few kilobytes of flash, a stack per task and a new class of bugs: races, deadlocks and priority inversion. Most non-trivial firmware is better off with one, and the smallest single-purpose devices are better off without.

What an RTOS gives you

Picture firmware for a small environmental sensor. It reads two sensors every 100 ms, filters the values, sends a summary over a radio every 10 seconds, answers commands on a serial port and blinks a status LED. Each of those has a different rhythm and a different way of waiting. In a main loop you interleave them by hand, and the radio's 80 ms wait for an acknowledgment stalls everything else.

An RTOS lets you write each activity as its own function, called a task, with its own loop:

sensor_tasks.cc
static void vSensorTask(void *pvParameters)
{
    TickType_t xLastWake = xTaskGetTickCount();
    (void) pvParameters;

    for (;;)
    {
        xTaskDelayUntil(&xLastWake, pdMS_TO_TICKS(100));
        read_and_filter();
    }
}

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

    for (;;)
    {
        vTaskDelay(pdMS_TO_TICKS(10000));
        radio_send_summary();          /* may block for 80 ms; nothing else notices */
    }
}

The radio task can sit in an 80 ms wait while the sensor task keeps its 100 ms rhythm, because the kernel switches to whichever task is ready. That separation is the core benefit: each activity's timing no longer depends on the sum of all the others.

Three more benefits follow from the same machinery. Structure: the code splits along the natural seams of the problem. Responsiveness: the highest-priority ready task runs, so urgent work is not stuck behind slow work. Power: when no task is ready, the kernel runs an idle task where you can put the processor to sleep, which a polling loop cannot do cleanly.

How an RTOS works inside

You do not need to read kernel source to use one, but four pieces are worth knowing because they explain nearly every behavior you will see.

The task control block and stack. Each task has a small record in RAM, the task control block, holding its state, priority and saved stack pointer. Each task also has its own stack, where its local variables live and where its registers are parked when it is not running. This is where the RAM cost comes from: a task is a stack plus a record.

The tick. A hardware timer, normally SysTick on Cortex-M, interrupts at a fixed rate, say 1,000 times a second. The kernel counts these ticks, and all of its time-based features, delays, timeouts and timers, are measured in ticks. The later post on tick rate shows how the rate affects delay resolution and power.

The scheduler. On each tick and each time a task blocks or unblocks, the scheduler picks the task to run: the highest-priority task that is ready. FreeRTOS keeps one list of ready tasks per priority and picks from the highest non-empty one, which takes the same time no matter how many tasks exist.

The context switch. To change tasks, the kernel saves the running task's registers on its stack, records the stack pointer in its control block, loads the next task's stack pointer and restores its registers. On Cortex-M, the hardware saves part of the context on exception entry, and a handler called PendSV does the rest, which the post on PendSV walks through instruction by instruction.

Put together: a timer interrupt fires, the kernel decides whether another task should run and, if so, requests the switch. The processor takes the PendSV exception, swaps the contexts and returns into the new task as if it had never stopped.

The four task states

A task is always in exactly one of four states, and understanding them solves most "why is my task not running" questions:

StateMeaningUses CPU
RunningExecuting on the processor right nowYes
ReadyAble to run, waiting for the CPU because a higher-priority task has itNo
BlockedWaiting for a delay to expire or an event such as a queue messageNo
SuspendedHeld out of scheduling until explicitly resumedNo

The task states post goes through each transition. The rule that follows is the one you should memorize: a task should spend most of its life Blocked. A task that never blocks and has a high priority starves everything below it.

What "real-time" actually means

An RTOS is not a fast operating system, and the name causes more confusion than any other term in the field. Real-time means the response to an event has a bounded worst case, not a good average. A motor controller that must update an output every 1 ms is correct if the update always lands within, say, 50 microseconds of its trigger. It is incorrect if it usually lands within 10 microseconds and occasionally within 3 ms, even though it is faster on average.

Three terms carry the idea. Latency is the time from an event to the start of its response. Jitter is how much that latency varies. A deadline is the latest acceptable completion time. A system is deterministic when you can state an upper bound on latency and it never exceeds it.

Deadlines come in classes by the cost of a miss:

  • Hard: a miss is a failure, as with an airbag or a brake controller.

  • Firm: a late result is worthless, but a single miss is survivable, like a dropped video frame.

  • Soft: a late result is still partly useful, as with a UI that responds slowly.

The classification, not the length of the deadline, decides how much analysis you owe. The posts on what makes an operating system real-time and on hard, soft and firm requirements give the full treatment. The practical consequence is that the properties an RTOS adds are about bounds: priority preemption, kernel calls with documented worst cases and very short interrupt-disabled sections.

From a main loop to an RTOS: when to switch

A main loop, or superloop, is the right first design and often the final one. It breaks when the response time of every feature becomes the sum of every function in the loop. Here is the arithmetic. Suppose one pass runs a 12 ms sensor read, a 30 ms display update, a 3 ms command parse and 1 ms of button handling. A button pressed just after the loop checked it waits up to 46 ms. If the requirement is 20 ms, no amount of tuning inside one function fixes it, because the problem is the sum.

The usual workaround is to split long functions into state machines that do a little each pass. That works, and it turns straight-line code into tangles of switch statements. An RTOS replaces the hand-written scheduler with a tested one.

Signs that you are at the point of switching:

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

  2. You have written several state machines purely to avoid blocking.

  3. Timing needs 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.

  5. More than one engineer edits the loop, and merge conflicts live there.

The comparison post on superloops and RTOSes shows the same firmware both ways and a decision table. A second post shows how to convert existing flag-polling firmware into tasks in five steps, so the product keeps working at every commit.

Your first FreeRTOS program

A complete program with two tasks shows every moving part. This blinks two LEDs at different rates, using one task function and a parameter to tell the two apart:

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

typedef struct {
    uint8_t  led;
    uint32_t period_ms;
} blink_cfg_t;

static const blink_cfg_t cfgGreen = { 0, 500 };
static const blink_cfg_t cfgRed   = { 1, 1000 };

static void vBlinkTask(void *pvParameters)
{
    const blink_cfg_t *cfg = (const blink_cfg_t *) pvParameters;

    for (;;)
    {
        led_toggle(cfg->led);
        vTaskDelay(pdMS_TO_TICKS(cfg->period_ms));
    }
}

int main(void)
{
    BaseType_t ok;

    board_init();

    ok = xTaskCreate(vBlinkTask, "green", 128, (void *) &cfgGreen, 1, NULL);
    configASSERT(ok == pdPASS);
    ok = xTaskCreate(vBlinkTask, "red", 128, (void *) &cfgRed, 1, NULL);
    configASSERT(ok == pdPASS);

    vTaskStartScheduler();
    for (;;) { }                       /* reached only if the scheduler could not start */
}

Read it as a recipe. xTaskCreate takes the function, a name, a stack depth in words, a parameter, a priority and an optional handle. Create all your tasks before the scheduler, call vTaskStartScheduler, and it takes over: it creates the idle task, starts the tick and launches the highest-priority ready task. The call returns only if the kernel ran out of heap for its own tasks.

Two details save hours. The stack depth is in words, so 128 means 512 bytes on a 32-bit core. And vTaskDelay blocks the task for a number of ticks, so pdMS_TO_TICKS converts milliseconds, rounding down, which at a low tick rate can turn a short delay into zero.

The dedicated post on xTaskCreate covers every parameter, the stack-size guess and the three beginner mistakes: a task function that returns, a stack that is too small and an unchecked return value.

The configuration file

Every FreeRTOS project needs a FreeRTOSConfig.h that sets the clock, the tick rate, the number of priorities and the heap size, among dozens of other settings. A minimal core looks like this:

FreeRTOSConfig.hc
#define configUSE_PREEMPTION        1
#define configCPU_CLOCK_HZ          ( SystemCoreClock )
#define configTICK_RATE_HZ          ( ( TickType_t ) 1000 )
#define configMAX_PRIORITIES        ( 7 )
#define configMINIMAL_STACK_SIZE    ( ( uint16_t ) 128 )
#define configTOTAL_HEAP_SIZE       ( ( size_t ) ( 24 * 1024 ) )
#define configASSERT( x )           do { if( ( x ) == 0 ) { taskDISABLE_INTERRUPTS(); for( ;; ); } } while( 0 )

#define vPortSVCHandler             SVC_Handler
#define xPortPendSVHandler          PendSV_Handler
#define xPortSysTickHandler         SysTick_Handler

Define configASSERT from the first build. The kernel checks a great deal with it, from interrupt priorities to queue misuse, and without it every one of those faults shows up later as a crash somewhere else. The configuration post lists every group of settings and what goes wrong with each. The post on the three handler names explains why the scheduler hangs when they are unmapped.

Priorities and scheduling

The scheduler's rule is simple: run the highest-priority ready task, and among equals take turns. The consequences are not, and priority assignment is where designs succeed or fail.

Preemptive and cooperative

In a preemptive kernel, a task that becomes ready and outranks the running one takes the CPU at once. In a cooperative kernel, tasks switch only when the running one blocks or yields. Preemption gives better response, and it means shared data needs protection, because a switch can land between any two instructions. Cooperation removes many races and lets a runaway task freeze everything. FreeRTOS selects the mode with configUSE_PREEMPTION, and the dedicated post compares them with a concrete race. Almost all products with deadlines use preemption.

Equal priorities and time slicing

With configUSE_TIME_SLICING set to 1, tasks of equal priority alternate each tick. With it off, an equal-priority task runs until it blocks. Turning it off saves context switches and gives equal tasks implicit mutual exclusion, and it also lets a compute-bound task starve its peers, so leave it on unless you have a documented reason.

Assigning priorities

For periodic tasks, the standard starting point is rate-monotonic ordering: the shorter the period, the higher the priority. For event-driven tasks, order by how quickly the event needs a response, not by how important it is. A log writer may be vital and still have all the time in the world.

A conservative template:

LevelWho belongs hereBehavior
HighHardware event handlers with tight timingShort, always blocked between events
Medium-highControl loops with deadlinesPeriodic, bounded work
MediumApplication logic and command handlingMostly blocked on queues
LowLogging, display refresh, background workMay run longer
IdleThe kernel's idle taskAlways ready

Keep the number of levels small, four to six, and define them as named constants in one header so the policy lives in one place. The post on task boundaries and priorities works a full example, a sensor node, through five rules for splitting firmware into tasks, and the post on choosing priorities without starving lower tasks reproduces starvation in 30 lines so you can recognize it.

How the kernel picks the next task

The selection must be fast, since it runs on every switch. FreeRTOS keeps an array of ready lists indexed by priority and a bitmap of which priorities have ready tasks. On Cortex-M, the port finds the highest set bit with the CLZ instruction in constant time. Inside each priority, a rotating pointer steps to the next entry, so equal-priority tasks take turns without any searching. The internals post reads the real source, and the takeaway for application code is that the cost of picking a task does not grow with the number of tasks.

Talking between tasks

Tasks that never communicate are rare. The kernel supplies a small set of objects for it, and picking the right one avoids most concurrency bugs. The cheat sheet post lists each primitive with a "when not to" line; here is the working summary.

Queues carry data

A queue is a fixed-size FIFO that copies items in and out. One task sends, another receives, and the kernel handles waiting. Because the copy happens inside the kernel, the sender can reuse its variable immediately, and nobody shares a buffer by accident.

queue_basic.cc
typedef struct { uint8_t channel; uint16_t value; } adc_sample_t;

static QueueHandle_t xSamples;

void queues_init(void)
{
    xSamples = xQueueCreate(16, sizeof(adc_sample_t));
    configASSERT(xSamples != NULL);
}

static void vAcquireTask(void *p)
{
    uint16_t counter = 0;
    (void) p;
    for (;;)
    {
        adc_sample_t s = { .channel = 1, .value = counter++ };
        if (xQueueSend(xSamples, &s, pdMS_TO_TICKS(10)) != pdPASS)
        {
            samples_dropped++;
        }
        vTaskDelay(pdMS_TO_TICKS(100));
    }
}

static void vProcessTask(void *p)
{
    adc_sample_t s;
    (void) p;
    for (;;)
    {
        if (xQueueReceive(xSamples, &s, portMAX_DELAY) == pdPASS)
        {
            process(&s);
        }
    }
}

The processing task sits Blocked on the empty queue, using no CPU, until a sample arrives. The queue cluster later in this series covers every variant: sending from an interrupt, peeking without removing, queues of pointers for large buffers, stream buffers for byte flows and message buffers for framed packets. The first of those posts, on xQueueSend and xQueueReceive, is the place to start.

Task notifications wake a task cheaply

When you only need to wake one task, possibly with a number, a task notification is lighter than any other object: it lives inside the task control block and needs no allocation.

notify_basic.cc
void EXTI0_IRQHandler(void)
{
    BaseType_t xWoken = pdFALSE;
    clear_exti0();
    vTaskNotifyGiveFromISR(xButtonTask, &xWoken);
    portYIELD_FROM_ISR(xWoken);
}

static void vButtonTask(void *p)
{
    (void) p;
    for (;;)
    {
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
        handle_button();
    }
}

It targets exactly one task and cannot buffer separate values, which is why it does not replace queues.

Semaphores signal and count

A binary semaphore is a flag with a wait queue, used to signal that something happened. A counting semaphore holds a count, which suits counting events or limiting access to a pool of identical resources. Neither has an owner, which makes them right for signaling and wrong for locking.

Mutexes protect shared resources

When two tasks must not use a resource at the same time, such as an SPI bus or a shared data structure, use a mutex. A mutex has an owner, and only the owner may release it. FreeRTOS mutexes also apply priority inheritance.

mutex_basic.cc
static SemaphoreHandle_t xBusMutex;

void bus_init(void)
{
    xBusMutex = xSemaphoreCreateMutex();
    configASSERT(xBusMutex != NULL);
}

bool bus_transfer(const uint8_t *tx, uint8_t *rx, size_t len)
{
    if (xSemaphoreTake(xBusMutex, pdMS_TO_TICKS(50)) != pdPASS)
    {
        return false;               /* waited 50 ms and never got it */
    }

    spi_transfer(tx, rx, len);
    xSemaphoreGive(xBusMutex);
    return true;
}

Always use a timeout when taking a mutex in anything but a throwaway demo, so a stuck holder becomes a logged failure instead of a frozen task. Never take a mutex in an interrupt, and never hold one across a blocking call such as a queue wait, since that is how deadlocks begin.

Event groups wait for combinations

An event group is a set of bits that tasks set, clear and wait on, singly or together. Use one when a task must wait for several conditions, such as "radio up AND sensors calibrated", or when several tasks must start together. They carry no data.

Which one to pick

You want toUseNot
Pass data between tasks or from an ISRQueueA global variable with a flag
Wake one task, no dataTask notificationA binary semaphore, unless several wait
Protect a shared resourceMutexA binary semaphore
Count events or limit access to N itemsCounting semaphoreA queue of dummy items
Wait for several conditionsEvent groupSeveral semaphores polled in turn

Priority inversion and why mutexes matter

Suppose a low-priority task holds a lock that a high-priority task needs, and a medium-priority task keeps preempting the low one. The high-priority task waits on work that matters less than its own. This is priority inversion, and it is a documented cause of real system failures.

A mutex with priority inheritance fixes it: while the high-priority task waits, the holder temporarily runs at the waiter's priority, finishes its critical work and releases the lock. A binary semaphore does not do this, which is why it must not be used for locking. If you can design the problem away, do: keep high-priority tasks off locks that low-priority tasks hold, which a gatekeeper task that owns the resource achieves.

Interrupts and the RTOS

Interrupts run outside the scheduler. They preempt every task, and they have rules.

**Use only the FromISR functions.** Ordinary calls such as xQueueSend may block, and an interrupt cannot. Each ISR-safe call takes a flag, pxHigherPriorityTaskWoken, that tells you whether it made a higher-priority task ready. Initialize it to pdFALSE, and finish the handler with portYIELD_FROM_ISR(flag) so that task runs as soon as the interrupt returns instead of at the next tick.

Respect the syscall priority. On Cortex-M, the kernel masks interrupts at and below configMAX_SYSCALL_INTERRUPT_PRIORITY while it updates its own lists. An interrupt above that level is never masked, so it must not call the kernel. An interrupt left at the reset default of priority 0 is above the limit, and calling a FromISR function from it stops in an assertion in vPortValidateInterruptPriority. The fix is to set the interrupt's priority explicitly:

irq_priority.cc
#define IRQ_PRIO_UART   ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1 )

NVIC_SetPriority(USART2_IRQn, IRQ_PRIO_UART);
NVIC_EnableIRQ(USART2_IRQn);

The dedicated post on that assertion lists six causes and an audit helper that prints every enabled interrupt's priority.

Keep handlers short. Capture the data, clear the source, hand off to a task. The task's priority then decides when the heavy work happens relative to everything else. This split also keeps interrupt latency low, and the post on latency and jitter explains why the worst case matters more than the average.

Defer when you must. A very fast interrupt that has to sit above the syscall limit cannot call the kernel. It captures data and pends a low-priority software interrupt, which makes the kernel calls.

Memory: stacks, heap and static allocation

An RTOS multiplies your memory questions by the number of tasks.

Stacks

Each task needs a stack big enough for its deepest call chain plus an interrupt frame. Too small corrupts memory without warning, and too large wastes RAM. Do not guess. Create tasks with stacks you are sure are too big, run the firmware through its worst paths and read how much each one used with uxTaskGetStackHighWaterMark, which returns the minimum free stack in words since the task started. Subtract from the original size, add 25 to 50 percent, and set the final size. Turn on configCHECK_FOR_STACK_OVERFLOW as a safety net during development. The stack sizing post gives the procedure and a monitor you can drop in.

Surprises that eat stack: printf, which can need hundreds of words on small C libraries, big local arrays and the extra registers saved when a task uses the FPU.

Heap and static allocation

xTaskCreate and the other create functions take memory from the FreeRTOS heap, one of several implementations you add to the build. The common choice, heap_4.c, is first-fit with coalescing of free blocks. Its failure mode is fragmentation: enough total free memory but no block big enough. If the product must never fail to allocate, use static allocation, where you supply the stack array and the control block, so creation cannot fail and the linker map is a complete inventory.

static_task.cc
static StackType_t  xStack[256];
static StaticTask_t xTcb;

TaskHandle_t h = xTaskCreateStatic(vTask, "t", 256, NULL, 2, xStack, &xTcb);

The static-allocation post covers the idle and timer task memory callbacks, and the later heap posts compare the allocators. A habit worth adopting: create all tasks and objects at start-up and never delete them. If you must delete tasks, remember that the idle task frees their memory, so it must get CPU time, and anything the task allocated or holds, such as a mutex, is yours to release first.

Time: ticks, delays and timers

All kernel time is measured in ticks. Three consequences follow.

Resolution. A delay of n ticks lasts between n - 1 and n tick periods, because the call lands somewhere inside a tick. pdMS_TO_TICKS truncates, so at a 100 Hz tick, pdMS_TO_TICKS(5) is 0. If you need a minimum wait, add a tick.

Drift. vTaskDelay waits from the moment of the call, so a loop that does work and then delays has a period of work plus delay. For a fixed rate, use xTaskDelayUntil, which wakes at absolute times:

periodic.cc
static void vControlTask(void *p)
{
    TickType_t xLastWake = xTaskGetTickCount();
    const TickType_t xPeriod = pdMS_TO_TICKS(10);
    (void) p;

    for (;;)
    {
        BaseType_t xWasDelayed = xTaskDelayUntil(&xLastWake, xPeriod);
        if (xWasDelayed == pdFALSE)
        {
            overruns++;               /* the last pass ran past its deadline */
        }
        control_step();
    }
}

Software timers. For many small jobs that do not need their own stack, FreeRTOS provides software timers whose callbacks run in one shared timer task. Callbacks must never block and should be short. The comparison post on vTaskDelay, xTaskDelayUntil and timers gives the decision table.

Tick rate and power

A tick at 1,000 Hz wakes a sleeping core 1,000 times a second, which costs energy on a battery device. Tickless idle, enabled with configUSE_TICKLESS_IDLE, stops the tick when the idle task sees a long idle period and sleeps until the next event, then corrects the tick count on wake. The tick-rate post covers the trade-offs, and the later posts in the cluster on timers and tickless idle show the port-level details.

A worked design: the sensor node, end to end

Pull the pieces together on the sensor node from the start of this guide. The requirements: sample two sensors every 100 ms, send a summary every 10 seconds over a radio that can take 80 ms per transmission, accept commands on a UART and blink a status LED.

Step 1: find the independent timing sources. The 100 ms sampling, the 10 second radio schedule, the UART bytes and the LED are four different rhythms. The radio also blocks, waiting for an acknowledgment, which is a fifth reason to give it a task of its own.

Step 2: choose a mechanism for each hand-off. The UART interrupt places bytes in a stream buffer, and the command task reads from it. The sampler publishes its latest values through a length-one queue with xQueueOverwrite, and the radio task peeks at it when it builds a summary. A software timer blinks the LED, so it needs no stack of its own.

Step 3: assign priorities. The sampler has the shortest period and the tightest deadline, so it gets the highest application priority. The command task responds at human speed, so it sits in the middle. The radio task has the longest period and the longest blocking time, so it sits below the sampler. Flash logging, if present, takes the lowest level.

node_setup.cc
#define PRIO_RADIO     ( tskIDLE_PRIORITY + 1 )
#define PRIO_COMMAND   ( tskIDLE_PRIORITY + 2 )
#define PRIO_SAMPLER   ( tskIDLE_PRIORITY + 3 )

void app_start(void)
{
    BaseType_t ok = pdPASS;

    xLatest   = xQueueCreate(1, sizeof(reading_t));
    xRxStream = xStreamBufferCreate(128, 1);

    ok &= xTaskCreate(vSamplerTask, "sample", 256, NULL, PRIO_SAMPLER, NULL);
    ok &= xTaskCreate(vCommandTask, "cmd",    256, NULL, PRIO_COMMAND, NULL);
    ok &= xTaskCreate(vRadioTask,   "radio",  384, NULL, PRIO_RADIO,   NULL);

    TimerHandle_t xLed = xTimerCreate("led", pdMS_TO_TICKS(500), pdTRUE, NULL, vLedTimer);
    ok &= (xLed != NULL) && (xTimerStart(xLed, 0) == pdPASS);

    configASSERT(ok == pdPASS);
}

The &= accumulation works because pdPASS is 1 and pdFAIL is 0, so any failed creation clears the flag and the assertion stops the first run. That is a good habit on a small design: a heap that is too small shows up on the first boot instead of in the field.

Step 4: check the arithmetic. The sampler needs about 150 microseconds every millisecond-scale period, a small fraction of the CPU. The radio's 80 ms of blocking time costs no CPU, since the task is Blocked. The worst-case delay for the sampler is its own run time plus interrupt time, because nothing outranks it. That is a design you can defend with measurements.

Step 5: verify under load. Run the system with the radio retrying, the UART flooded and logging on. Read the stack margins, the queue high-water marks and the CPU report. Fix what the numbers show, and keep the counters in the build.

Mistakes nearly everyone makes once

A short list of the failures that appear in almost every first RTOS project, so you can recognize them when your turn comes.

A busy-wait inside a task. A loop that polls a register without blocking holds the CPU at its priority. Wait on an interrupt through a notification, or at least call a delay inside the loop.

Shared variables without protection. A volatile flag between an interrupt and one task is fine. A struct updated by two tasks is a race, and the failure is rare enough to survive testing. Use a queue, a mutex or a single owner.

Calling blocking functions from an interrupt or a timer callback. Interrupts have no context to sleep, and timer callbacks run in a shared task that everyone else's timers depend on. Use the FromISR calls in handlers and a zero block time in callbacks.

Priorities by importance. The log writer is important, and it has no deadline. Priority is about how quickly an event needs a response.

Guessed stack sizes. A stack that is too small fails far from its cause. Measure, add margin and turn on overflow checking in test builds.

Unchecked return values. Creation, sends and takes can fail. A system that ignores errQUEUE_FULL loses data without a trace.

Interrupt priorities left at the default. Priority 0 is the highest, so any peripheral enabled without a priority sits above the kernel limit.

Deleting tasks as a routine. Memory returns late, mutexes stay locked and handles dangle. Create once, and let tasks wait for work.

Debugging an RTOS application

Concurrency bugs depend on timing, so the debugging tools differ from bare-metal ones.

Assertions first. configASSERT turns a large share of kernel misuse into a stop on the offending line.

See the tasks. vTaskListTasks prints a table of every task with its state, priority and stack margin, which answers "what is each task doing" at a glance. It disables interrupts while it runs, so it is a development tool. For production, uxTaskGetSystemState returns raw numbers.

Measure the CPU. With run-time statistics enabled and a fast counter, the kernel records how long each task ran, giving a percentage per task including the idle task, whose share is your headroom. Report over a window, not since boot.

Trace the timeline. A trace tool such as SEGGER SystemView records every task switch and interrupt and draws them on a timeline. It shows starvation, inversion and jitter in a way text logs cannot, and each post in this cluster that mentions it is a reminder that printf changes the timing you are trying to see.

Probe with a pin. A GPIO toggled at the start and end of a code path, read on a logic analyzer, is the cheapest precise timing instrument there is. The post on measuring context-switch time uses it.

A short list of symptoms and likely causes:

SymptomLikely cause
A task never runsA higher-priority task never blocks, or the task is blocked on something that never happens
Hard fault soon after startStack too small, handlers not mapped or an interrupt calling the kernel at the wrong priority
Everything runs at the wrong speedconfigCPU_CLOCK_HZ does not match the real clock
Random corruption under loadShared data without a lock, or a stack overflow
Deleted tasks do not return memoryThe idle task is starved

A design checklist

Before shipping an RTOS-based firmware, walk this list.

  1. Every task blocks somewhere and has a documented reason for its priority.

  2. Every interrupt that calls the kernel has an explicit priority at or below the syscall limit.

  3. Every shared variable is protected, passed by queue or owned by one task.

  4. Every mutex is taken with a timeout and never held across a blocking call.

  5. Every stack size comes from a measurement plus a margin, with overflow checking on in test builds.

  6. Every queue length comes from a rate times worst-case latency calculation, with drop counters in place.

  7. configASSERT is defined, and the stack overflow and malloc-failed hooks stop the system in a defined state.

  8. A watchdog covers a task that stops running, since a starved task is otherwise silent.

  9. The tick rate, the heap size and the number of priorities each have a comment saying why.

Choosing an RTOS

FreeRTOS is the common first choice because the kernel is small, the API is compact and most silicon vendors ship it. Zephyr is a full platform with a driver model, devicetree and a large hardware catalog, and it asks you to adopt its build system. NuttX offers POSIX-style interfaces on a microcontroller. ThreadX is a compact kernel with a long certification history. The comparison post sets them side by side, and the rule it gives is to follow the constraint that is hardest to change: your vendor's SDK, the hardware catalog you need, POSIX compatibility or a certification path. If your product is regulated, choosing the kernel is part of the safety argument, and the post on certified versus open source RTOS options explains what a kernel certificate covers and what it does not.

Where an RTOS is the wrong tool

An RTOS is not free, and we think it is wrong in some cases.

A device with one or two interrupt-driven jobs and generous timing slack gains nothing from a scheduler. The sensor node that wakes on a timer, reads a value, transmits and sleeps is smaller and simpler without one. RAM is another limit: each task needs its own stack and control block, so ten tasks on a part with 2 KB of RAM can consume the whole memory. A cooperative scheduler or an event-driven design can keep the single-stack simplicity and remove the sliced state machines, and the post that builds a cooperative scheduler in about sixty lines of C shows how far that goes.

Certification can argue against an RTOS too: a loop with fixed, analyzable timing is easier to put through a review than a preemptive system with dynamic interactions. And a team new to concurrency may write a worse design with an RTOS than with a clear loop, in which case the clear loop is the better product.

The limits of this guide itself: it describes single-core Cortex-M with FreeRTOS. Symmetric multiprocessing, Zephyr's devicetree and Kconfig, Linux-class systems and safety-certified kernels each have their own series. The concepts transfer, and the APIs and the pitfalls do not always.

A route through this series

If you are new, read in this order. Start with what makes an operating system real-time and the comparison of superloops and an RTOS. Then move to the FreeRTOS task posts: creating your first tasks, task states, and the configuration file. Next come queues, then semaphores and mutexes, then events and notifications, then timers and tickless idle. When the basics are comfortable, read the scheduling internals, the PendSV context switch and the post that writes a minimal preemptive scheduler from scratch, since building one is the fastest way to understand why every rule above exists. The expert posts on the MPU, SEGGER SystemView and safety certification come last.

The cornerstone guides for FreeRTOS tasks and scheduling and for queues, stream buffers and message buffers sit between this overview and the single-topic posts, and each of them links down to its posts.

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.