In industrial IoT (IIoT), every connected sensor, actuator, or gateway relies on a microcontroller (MCU) subject to strict constraints: memory limited to a few tens or hundreds of kilobytes, modest clock frequency, sometimes battery-powered operation, and expected operation over several years without intervention. The choice and mastery of the real-time operating system (RTOS) directly determine the reliability, maintainability, and security of the product.
Backed by Amazon since 2017 under the free MIT license and compatible with more than 40 hardware architectures, FreeRTOS has established itself as a reference for professional embedded equipment. This guide brings together the architecture principles, hardware selection, memory management, low-power strategies, integration of industrial protocols, and qualification practices needed to deploy robust firmware in production.
Bare-metal or RTOS: when to switch to FreeRTOS
The bare-metal approach (main loop or super-loop) remains relevant for highly constrained microcontrollers (for example a Cortex-M0 with 8 KB of RAM) or for simple devices: reading a sensor at a fixed interval and transmitting the value over a serial port. However, as soon as a device must manage more than three asynchronous flows — radio reception, analog acquisition, hardware watchdog, serial communication, power management — the single loop quickly reaches its limits:
- Non-deterministic response times: a long operation (Flash memory write, network negotiation) blocks all other functions.
- Tight coupling: adding a feature often requires rethinking the balance of the entire loop.
- Complex debugging: without task-level isolation, the source of a deadlock is hard to pinpoint.
- Costly maintenance: the code loses readability as edge cases accumulate.
With FreeRTOS, each function becomes an independent task with its own stack, priority, and execution context. Exchanges go through formalized primitives (message queues, semaphores, event groups) and the preemptive scheduler always runs the highest-priority ready task.
Software architecture and task design
Layered organization
A maintainable IIoT firmware is organized into five clearly separated layers:
- Hardware layer: microcontroller (STM32, ESP32, RP2040/RP2350), buses and peripherals (GPIO, ADC, SPI, I²C, UART, DMA, CAN), sensors, and radio modules.
- BSP / HAL: manufacturer abstraction layer (STM32Cube HAL, ESP-IDF, Pico SDK) that isolates hardware registers.
- FreeRTOS kernel: scheduler, memory management, synchronization, software timers, and sleep management.
- Middleware: network and application stacks (LwIP, MQTT, CoAP), cryptography (mbedTLS), file system (NVS, SPIFFS, LittleFS), and OTA updates.
- Application layer: business tasks (acquisition, filtering, communication, supervision, and diagnostics).
Clean interfaces between these layers allow a component to evolve — changing a sensor or network stack — without rewriting the business logic.
Task granularity and priorities
Creating one task per feature unnecessarily increases the memory footprint (stack and task control block), multiplies context switches, and complicates synchronization. The practical rule is to dedicate one task per independent and asynchronous execution flow. Two operations sharing the same cadence and resources are better off coexisting in a single task driven by a state machine.
Example of a common breakdown for a connected industrial node:
- Acquisition task (high priority, 100 ms period): reads sensors via ADC, SPI, or I²C, applies filtering, and deposits measurements into a queue.
- Communication task (medium priority): consumes the queue, formats frames, and manages network transmission (MQTT, LoRaWAN, or Modbus).
- Supervision task (low priority): manages configuration, logs, and the diagnostic interface.
- Watchdog task: monitors the health of application tasks and triggers a clean shutdown sequence before reset in case of a deadlock.
Scheduling, periodicity, and real-time latency
FreeRTOS relies on a preemptive fixed-priority scheduler (from 0 to configMAX_PRIORITIES - 1). For periodic sampling without cumulative drift, prefer vTaskDelayUntil() over vTaskDelay(), which shifts the period at each execution.
Actual determinism, however, depends on three parameters:
- Interrupt latency: critical sections (taskENTER_CRITICAL()) mask interrupts. Keeping them beyond a few microseconds degrades hardware responsiveness.
- Tick frequency: a 1 kHz (1 ms) tick interrupt increases CPU load. In an industrial environment, a 100 Hz (10 ms) tick covers most needs. For fast control loops (servo control, motor drive), a dedicated hardware timer outside FreeRTOS remains preferable.
- Tickless idle mode: it suspends ticks when all tasks are blocked to reduce power consumption, at the cost of coarser time granularity.
Microcontroller selection and hardware specifics
FreeRTOS runs on virtually all MCUs on the market. The component choice therefore responds to connectivity, power consumption, peripheral, and project longevity constraints.
| Platform | Strengths | Limitations | Typical use cases |
|---|---|---|---|
| STM32 (STMicroelectronics) | Wide range (Cortex-M0 to M33/M7), industrial peripherals (CAN-FD, Ethernet MAC, USB HS), low-power range (STM32U5), tooling suited to functional safety requirements | No native wireless connectivity on classic series, sometimes complex middleware stacks, higher unit cost | PLCs, industrial controllers, battery-powered autonomous sensors, critical systems |
| ESP32-S3 (Espressif) | Integrated Wi-Fi and Bluetooth, hardware cryptographic acceleration, dual-core, ESP-IDF ecosystem shipped with FreeRTOS | Deep sleep consumption around 10 µA (higher than ultra-low-power MCUs), no native CAN-FD, dependency on Espressif tooling | IoT gateways, Wi-Fi connected devices, lightweight local processing |
| RP2040 / RP2350 (Raspberry Pi) | Very low unit cost (around $1), programmable PIO blocks to emulate specific protocols, clear documentation | Limited industrial peripherals (no native CAN, only one ADC on RP2040), less direct FreeRTOS integration than under ESP-IDF | High-volume cost-constrained products, rapid prototyping, custom interfaces |
FreeRTOS specifics on ESP32 (ESP-IDF)
On ESP32 and its variants (S3, C6, H2), FreeRTOS is integrated directly into the ESP-IDF framework with three specifics to master:
- SMP scheduling: on dual-core chips, tasks can run on either core, with affinity configurable via xTaskCreatePinnedToCore(). By convention, core 0 hosts the Wi-Fi/Bluetooth stacks and core 1 runs the application.
- Deferred interrupts: network callbacks (Wi-Fi, MQTT, HTTP) are delivered as events to dedicated tasks to reduce time spent in interrupt context.
- Dual memory allocator: the FreeRTOS heap coexists with ESP-IDF's multi-region allocator (heap_caps_malloc() for DMA or PSRAM memory). Never mix pvPortMalloc() and malloc() within the same allocation and free.
Memory management and inter-task communication
Choosing the right allocation scheme (heap_1 to heap_5)
Heap (heap) fragmentation and stack overflows are among the most common causes of failure in production, as they often appear only after several weeks of continuous operation. FreeRTOS offers five allocation schemes:
- heap_1: allocation without free. No fragmentation, suited to firmwares that allocate all resources at startup.
- heap_2: allocation and free without merging adjacent blocks. Prone to fragmentation, to be avoided for prolonged operation.
- heap_3: wraps the C library's malloc() and free(), with no real-time guarantee.
- heap_4: first-fit algorithm with merging of adjacent free blocks. This is the recommended default choice for industry.
- heap_5: same principle as heap_4 across multiple non-contiguous memory regions (internal SRAM, external SRAM, or TCM memory).
In production, use heap_4 with at least 30% headroom above the measured peak, enable configUSE_MALLOC_FAILED_HOOK to immediately intercept any allocation failure, or prefer static allocation (configSUPPORT_STATIC_ALLOCATION) on critical equipment to eliminate all dynamic allocation after startup.
Sizing stacks without approximation
An undersized stack causes random memory corruption; an oversized stack wastes precious RAM. The reliable method boils down to four steps:
- Start with a generous estimate (for example 256 32-bit words, i.e. 1 KB, for a simple task, and up to 4,096 words for a network or cryptographic task).
- Enable configCHECK_FOR_STACK_OVERFLOW in method 2, which checks a sentinel pattern at the end of the stack.
- Measure the actual headroom with uxTaskGetStackHighWaterMark() after at least 48 hours of testing under load.
- Adjust each stack to retain 20 to 30% headroom above the observed peak.
Synchronization primitives
The choice of communication primitive determines code readability and safety. Never share a global variable between tasks without a mutex or atomic operation: even a 32-bit integer access can become inconsistent depending on alignment and concurrent access.
| Primitive | Main use | Watchpoint |
|---|---|---|
| Queue | Copy-based data transfer between tasks (e.g. sensor measurement to network task) | Undersizing causing losses. Define an explicit wait timeout and check the return code. |
| Binary Semaphore | Simple synchronization between an ISR and a task ("data ready", "timer expired") | Does not handle priority inheritance: do not use to protect a shared resource. |
| Counting Semaphore | Tracking a finite number of resources (free buffers, accumulated events) | Risk of saturation if releases exceed consumptions; bound the maximum value. |
| Mutex | Exclusive access to a shared resource (SPI bus, UART, external memory) | Includes priority inheritance, but cannot be used from an interrupt. |
| Event Group | Combined wait for multiple events (e.g. sensor ready and network connected) | Limited to 24 bits with 32-bit ticks (or 8 bits if configUSE_16_BIT_TICKS is enabled). |
| Task Notification | Direct signaling to a task, very fast and with no memory overhead | Suited for targeted notifications; prefer a queue when multiple producers send structured data. |
The five classic pitfalls in production
- Unhandled priority inversion: a high-priority task waits for a resource held by a low-priority task, itself preempted by a medium-priority task. Always use a mutex (xSemaphoreCreateMutex(), with priority inheritance) rather than a binary semaphore to protect a shared resource.
- Blocking calls in an ISR: an interrupt routine must never call vTaskDelay() or any blocking function. Only use the FromISR-suffixed variants (such as xQueueSendFromISR() or xSemaphoreGiveFromISR()) followed by portYIELD_FROM_ISR(), and offload heavy processing to a dedicated task.
- Silent stack overflow: without active detection, an overflow corrupts neighboring memory and causes erratic restarts often wrongly attributed to hardware. Always enable stack checking during qualification.
- Brutal watchdog trigger: a hardware watchdog is essential, but a reset without cleanly closing connections, synchronizing non-volatile memory, or securing outputs can leave actuators in a dangerous state or corrupt data. Plan a controlled shutdown sequence.
- Long processing in software timers: all software timers run in a single kernel task (prvTimerTask). A blocking call in a callback freezes all timers in the system. Limit callbacks to a few microseconds and delegate long operations to a dedicated task.
Low-power strategies for battery-powered nodes
Microcontroller sleep modes
On modern low-power MCUs (such as the STM32U5 family), several sleep levels allow adjusting the trade-off between wake-up time and current draw:
- Sleep: CPU core halted, peripherals active, wake-up under 1 µs, consumption from a few tens to a hundred microamps per megahertz depending on the family.
- Stop: regulator in low-power mode, SRAM and registers retained, wake-up in a few microseconds, consumption on the order of a few microamps (often around 5 µA).
- Standby: only backup SRAM is maintained, wake-up equivalent to a restart, consumption on the order of 100 nA.
- Shutdown: internal power cut except for wake-up pins or real-time clock, consumption of a few tens of nanoamps.
Tickless idle and autonomous peripherals
By enabling configUSE_TICKLESS_IDLE in FreeRTOSConfig.h and implementing portSUPPRESS_TICKS_AND_SLEEP(), FreeRTOS programs a low-power timer (or the real-time clock) for the expected idle duration, then switches the MCU to Stop mode until the deadline or the next external interrupt.
To further reduce processor active time, exploit the autonomous peripherals available on recent MCUs: LPDMA (direct transfer from ADC to SRAM while the CPU sleeps), LPTIM / LPUART (counting and serial communication active in Stop mode), and programmable gain amplifiers (PGA) to condition the signal without waking the core.
Duty-cycling calculation and battery life estimation
The average current over a cycle composed of an active phase (I_active for t_active) and a sleep phase (I_sleep for t_sleep) is written as:
I_average = (I_active × t_active + I_sleep × t_sleep) / (t_active + t_sleep)
For example, with a 2,500 mAh battery, an active phase of 50 mA for 10 ms and a sleep of 5 µA for 9,990 ms, the average current settles at approximately 55 µA, i.e. over 5 years of theoretical battery life (excluding battery self-discharge and radio peaks). This calculation requires validating every milliampere in the lab, as a misconfigured pin or a forgotten peripheral is enough to divide battery life by ten.
Industrial connectivity: wired, wireless, and application layer
Wired buses: Modbus RTU, CAN, and industrial Ethernet
In workshops and fixed installations, wired links remain dominant for their reliability and immunity to interference:
- Modbus RTU (RS-485): typically handled in a periodic master task (10 ms to 1 s polling) using DMA on the UART, a semaphore to wait for the response with timeout, and a mutex if the bus is shared.
- CAN and CAN-FD: natively present on many STM32 and NXP MCUs (up to 8 Mb/s in CAN-FD), with open-source stacks like CANopenNode. Frames are captured in ISR then pushed to a queue toward a business decoding task.
- Ethernet and TCP/IP (LwIP): the Lightweight IP stack integrates with FreeRTOS via a dedicated network task responsible for feeding received packets and handling TCP timeouts.
Wireless protocols: range, throughput, and consumption
The choice of a radio link depends on the trade-off between range, throughput, power consumption, and available infrastructure:
| Protocol | Typical range | Throughput | RX consumption | Use case |
|---|---|---|---|---|
| LoRaWAN | 2 to 15 km | 0.3 to 50 kb/s | ~10 mA | Remote sensors, counting, isolated sites |
| BLE 5.4 | 10 to 100 m | 125 kb/s to 2 Mb/s | ~3 mA | On-site diagnostics, maintenance, mobile terminals |
| Thread (802.15.4) | 30 to 100 m | 250 kb/s | ~8 mA | Mesh networks of sensors and actuators in buildings |
| Wi-Fi HaLow (802.11ah) | 100 m to 1 km | 150 kb/s to 4 Mb/s | ~20 mA | Long-range gateways, larger data streams |
On constrained Cortex-M4 MCUs, a lightweight BLE stack like NimBLE (Apache Mynewt) keeps its footprint under 16 KB of RAM depending on configuration. In a cellular (4G Cat-1) or classic Wi-Fi environment, the network task must handle outages by locally buffering events and reconnecting progressively.
Application layer: MQTT and CoAP
MQTT over TLS (port 8883) dominates industrial telemetry reporting. In a FreeRTOS architecture, the network stack runs in a dedicated task fed by a priority output queue (to let alarms through before routine telemetry), with QoS 1 and an exponential backoff reconnection policy. CoAP over DTLS is a relevant alternative on constrained links with low bandwidth. This task-based separation facilitates the implementation of multi-protocol gateways capable of converting Modbus registers from a PLC into MQTT messages toward a supervision platform.
Embedded security and OTA updates
A compromised connected device represents an entry point into the operational network. The chain of trust must be designed from the prototype phase, especially since hardware activation of secure boot and Flash encryption on certain MCUs (via eFuses) is irreversible:
- Protected key storage: OTP (One-Time Programmable) memory or a dedicated secure element (ATECC608, SE05x) rather than cleartext Flash memory.
- Secure Boot: cryptographic verification (RSA or ECDSA) of the firmware signature at each boot.
- Flash Encryption: hardware encryption (AES-XTS on ESP32-S3) protecting the binary and secrets in case of physical access.
- Encrypted communications: TLS 1.3 for MQTT, DTLS for CoAP, AES-128/256 encryption on proprietary radio links, optionally complemented by cryptographic attestation of the device.
- Dual-partition OTA updates: encrypted download into an inactive partition (slot A / slot B), integrity check (CRC32 and ECDSA signature via mbedTLS) by the bootloader, and automatic rollback to the previous version in case of boot failure.
To dive deeper into the implementation of these mechanisms, consult our dedicated guide on industrial IoT firmware security: secure boot, Flash encryption, and OTA.
Debugging, qualification, and industrial best practices
Trace and diagnostic tools
Real-time problems (priority inversions, intermittent deadlocks, queue saturations) are rarely diagnosed with simple messages on a serial port. Four tool families prove decisive:
- Tracealyzer (Percepio) and SEGGER SystemView: chronological visualization of context switches, mutexes, queues, and interrupts over long sessions.
- SEGGER RTT: log emission via the SWD interface without a dedicated UART port and without blocking the processor.
- FreeRTOS+Trace and embedded metrics: tracking CPU load per task (ulTaskGetRunTimeCounter()), stack and queue fill levels, and allocation failures, ideally reported remotely to anticipate drift.
- GDB and OpenOCD over JTAG/SWD: step-by-step debugging and inspection of internal kernel structures, detailed in our guide on professional embedded debugging with JTAG, OpenOCD, and GDB.
In operation, saving a crash dump (CPU registers and task state in RTC memory or Flash, like the ESP-IDF panic handler) considerably speeds up the analysis of an incident that occurred on site.
Testing, power profiling, and software quality
Moving from prototype to industrial product requires systematic qualification discipline:
- Host-based unit tests: compile business logic with GCC and frameworks like Ceedling and Unity to validate filters, parsers, and state machines independently of hardware.
- Robustness testing: maximum simultaneous load, repeated network outages and power losses, 7 to 30-day continuous endurance tests, and fault injection (invalid frames, saturated buffers).
- Power profiling: measure actual current with an oscilloscope or a dedicated analyzer (Otii Arc, Power Profiler Kit II) by toggling a trace GPIO pin before and after each phase of the cycle to spot any hidden leak (active peripheral, forgotten pull-up resistor).
- MISRA-C:2023 coding rules: prohibition of dynamic allocation after initialization, exhaustive coverage of switch statements, strict control of pointer casts, and systematic handling of all FreeRTOS return codes (pdPASS, pdFAIL, errQUEUE_FULL).
- Continuous integration and hardware-in-the-loop (HIL): automated per-target compilation, unit test execution, then automated flashing and validation on real hardware.
- Task plan documentation: beyond five tasks, maintain a table listing name, priority, stack size, shared peripherals, and synchronization primitives to facilitate code reviews and handover to a new developer.
Case study: industrial vibration measurement node
To illustrate the combination of these principles, consider a vibration monitoring sensor built around an ADXL357 accelerometer, an STM32U585 microcontroller (Cortex-M33 with TrustZone), and an SX1262 radio transceiver:
- FreeRTOS architecture: five distinct tasks (sensor acquisition, FFT computation, LoRaWAN transmission, watchdog, and diagnostic console).
- Power management: 0.1% active duty cycle (1 ms of activity for 999 ms in Stop mode with tickless idle and DMA).
- Connectivity: LoRaWAN class A with a compacted 16-byte payload (spectral indicators and timestamp).
- Target battery life: powered by two lithium AA batteries (3,000 mAh), achieving several years of operation — up to approximately 8 years under nominal emission and temperature conditions.
Conclusion
FreeRTOS provides a proven foundation for structuring reliable industrial IoT firmwares, but the kernel alone guarantees neither determinism nor longevity in the field. The difference between a prototype and equipment that operates for years lies in engineering rigor: coherent MCU selection, verified memory sizing, prevention of real-time pitfalls, mastery of low-power modes, a complete security chain, and automated qualification.


