# FreeRTOS task design for small connected devices

> Practical FreeRTOS task design for small connected devices: task boundaries, queues, priorities, stack sizing and low power.

- Author: Milo Perović, Founder & lead engineer
- Published: 2026-11-10
- Topic: Firmware

Most firmware we are asked to rescue does not fail because FreeRTOS is hard. It fails because nobody sat down and decided what the tasks were for. Good FreeRTOS task design is mostly a set of boring decisions made early: how many tasks, who owns which peripheral, how data moves between them and how much stack each one really needs.

This post is for firmware engineers and technical founders building small connected devices on parts such as the STM32L4, nRF52840 or ESP32-S3. It is the structure we reach for when a product has a sensor, a radio, some storage and a battery to look after.

## Start from responsibilities, not from tasks

The common mistake is one task per peripheral: an I2C task, a UART task, an LED task, a button task. Ten tasks later, every one of them needs data from three others and the queues look like a plate of spaghetti. Each task also costs its own stack, which on a part with 64–256 KB of RAM adds up quickly.

We prefer to group work by responsibility and by timing. A typical battery-powered sensor node ends up with something like this:

- **Sensor task**: owns the sensor buses, runs the sampling schedule and produces measurements.

- **Connectivity task**: owns the radio stack interface, batches outgoing data and handles reconnects.

- **Storage task**: the only code that writes to flash, so writes are serialised and wear is controlled.

- **System task**: power states, buttons, LEDs, battery monitoring and the watchdog check-in logic.

Four or five application tasks is plenty for most devices. Vendor stacks will add their own (BLE host, Wi-Fi, TCP/IP, the timer service task), so count those too before you decide your design is lean.

## One owner per resource

The rule that saves the most debugging time is simple: every peripheral and every piece of shared state has exactly one owning task. Other tasks ask the owner to do something by sending it a message. They never touch the bus or the struct directly.

This removes most of the need for mutexes. Where you do need one, for example a SPI bus shared by flash and a display, use a FreeRTOS mutex rather than a binary semaphore. Mutexes implement priority inheritance, which limits priority inversion when a low-priority task holds the bus and a high-priority task is waiting for it. Binary semaphores do not, and that difference has produced some of the strangest intermittent stalls we have seen on the bench.

Keep critical sections short. Disabling interrupts to update a 32-bit counter is fine; doing it around a flash erase is not.

## Moving data between tasks

FreeRTOS gives you several mechanisms, and each fits a different job. Picking the right one keeps both RAM use and latency predictable.

MechanismBest forWatch out for

QueueFixed-size messages, commands, measurementsItems are copied; large structs waste RAM and time

Direct task notificationSignalling one task, ISR-to-task wake-ups, simple countersOnly one receiving task; limited to a 32-bit value per index

Stream or message bufferByte streams such as UART receive dataDesigned for a single writer and a single reader

Event groupWaiting on combinations of conditions, e.g. "network up and time synced"Not for passing data; heavier than notifications

Our default is a single command queue per task carrying a small tagged struct: a message type plus a union of payloads. Each task then has one blocking call at the top of its loop, which makes behaviour easy to reason about and easy to log. For large buffers, pass a pointer to a pool-allocated block and make ownership transfer explicit in the message type.

## Interrupts should be short and boring

An interrupt handler should capture what happened and wake the task that cares. That usually means reading a status register, clearing the flag, maybe copying a few bytes, then calling `vTaskNotifyGiveFromISR()` or `xQueueSendFromISR()` and requesting a context switch if a higher-priority task was woken.

Two details catch people out on Cortex-M parts. First, only use the `FromISR` API variants inside interrupts. Second, any interrupt that calls FreeRTOS functions must have a priority numerically equal to or greater than `configMAX_SYSCALL_INTERRUPT_PRIORITY`, which means logically lower urgency. Get this wrong and you will see rare corruption of kernel lists rather than a clean crash. Enabling `configASSERT()` during development catches most of these misconfigurations immediately.

## Priorities with a reason behind each one

In FreeRTOS a higher number means a higher priority, and the scheduler always runs the highest-priority ready task. If that task never blocks, nothing below it runs. So priorities should reflect deadlines, not importance.

- Highest: tasks with hard timing, such as servicing a sensor FIFO before it overflows.

- Middle: connectivity and storage, which need to be responsive but tolerate tens of milliseconds of delay.

- Low: housekeeping, LED patterns, diagnostics and anything that can wait.

Write the reason for each priority in a comment next to the task creation call. When someone later bumps a task up "to make it faster", the comment is the conversation they need to have first.

## Sizing stacks and heap in FreeRTOS task design

Stack sizes picked by guesswork are the most common source of mysterious resets we find in audits. Measure them instead. Run the device through its worst-case paths, including a radio reconnect, an OTA download and a full log flush, then read `uxTaskGetStackHighWaterMark()` for every task. Keep a margin of roughly 25–50% above the measured peak, more for tasks that call into vendor libraries or use `printf`-style formatting.

Note the units. In standard FreeRTOS the stack depth passed to `xTaskCreate()` is in words, so 512 on a 32-bit part means 2 KB. ESP-IDF's port takes the value in bytes. Copying a stack size between the two is an easy way to end up with a task a quarter of the size you intended, or four times larger.

During development, set `configCHECK_FOR_STACK_OVERFLOW` to 2 and implement the hook so it logs the task name before resetting. Pair it with the crash logging we described in [firmware crash logs that make field failures debuggable](https://miloperovic.com/journal/firmware-crash-logs-that-make-field-failures-debuggable/), and a stack overflow in the field becomes a one-line diagnosis instead of a week of guessing.

For memory, we create long-lived tasks and queues once at boot and never delete them. Static allocation with `xTaskCreateStatic()` makes RAM use visible at link time. If you use the heap, `heap_4` coalesces free blocks and is a sensible default; check `xPortGetMinimumEverFreeHeapSize()` after long soak tests to see how close you came to running out.

## Tasks, power and the watchdog

On a battery device, the task structure decides how often the core can sleep. Every task that wakes on a fixed `vTaskDelay()` poll pulls the processor out of low-power mode, whether or not there is work to do. Block on events instead, and enable tickless idle (`configUSE_TICKLESS_IDLE`) so the kernel can stop the tick and sleep until the next timeout. On many low-power MCUs the vendor port, or a small custom hook, is needed to enter the deepest stop modes.

The watchdog needs the same thought. Feeding it from a single low-priority task only proves that task runs. A better pattern is for each critical task to check in with the system task, which feeds the hardware watchdog only when all of them have reported recently. We cover that pattern in more depth in [our post on firmware watchdog design](https://miloperovic.com/journal/firmware-watchdog-design-that-recovers-devices-in-the-field/).

## What we would do on a new project

Before writing much application code, we put the following on one page and review it with the whole team:

- A list of tasks, each with a single responsibility, its owned peripherals and its priority with a reason.

- One command queue per task with a defined message format, plus notifications for ISR wake-ups.

- A rule that no two tasks touch the same peripheral or shared struct without a mutex or a message.

- Interrupt priorities checked against `configMAX_SYSCALL_INTERRUPT_PRIORITY`, with `configASSERT()` enabled.

- Measured stack high-water marks after worst-case testing, with margins recorded in the code.

- No polling loops in steady state, tickless idle enabled, and a multi-task watchdog scheme.

None of this is clever. That is the point: a firmware architecture that a new engineer can understand in an afternoon is one that keeps working when the product ships and the edge cases start arriving.
