Firmware
RTOS Selection Guide: Zephyr vs FreeRTOS for Modern Embedded Systems
Comprehensive Technical Comparison for IoT, Industrial, and Safety-Critical Applications in 2025
“The RTOS decision is not merely technical—it shapes your team’s development velocity, silicon vendor relationships, and long-term product evolution. We’ve deployed both FreeRTOS and Zephyr in production across hundreds of IoT and industrial projects, and each excels in fundamentally different contexts.”
Contents· 12 sections
Executive Summary
The selection of a Real-Time Operating System (RTOS) represents one of the most consequential architectural decisions in embedded systems development. This choice fundamentally shapes development timelines, long-term maintenance costs, hardware flexibility, and ultimately, product success in the marketplace. As the embedded systems landscape continues its rapid evolution toward connected, intelligent devices, the RTOS decision has grown increasingly complex, with implications extending far beyond simple task scheduling into cloud connectivity, security certification, and ecosystem integration.
This white paper provides a rigorous technical comparison between two dominant open-source RTOS platforms: FreeRTOS, the industry incumbent with over two decades of deployment history and Amazon Web Services backing, and Zephyr, the ambitious Linux Foundation project that has rapidly emerged as a formidable alternative with strong backing from Intel, Nordic Semiconductor, and the broader open-source community.
Key Findings
FreeRTOS remains the optimal choice for projects requiring:
- Minimal memory footprint (as low as 4-9KB ROM, 1KB RAM for basic configurations)
- Rapid prototyping and time-to-market acceleration on resource-constrained microcontrollers
- Deep AWS IoT Core integration with pre-certified libraries
- Legacy system compatibility and proven production stability
- Simple, well-understood programming model with extensive community support
- Projects needing a pre-certified kernel today (SAFERTOS: IEC 61508 SIL 3, ISO 26262 ASIL D)
Zephyr emerges as the superior platform for:
- Complex, multi-protocol IoT devices requiring Bluetooth, Thread, and Matter support
- Hardware abstraction needs spanning 600+ supported boards from 50+ vendors
- Projects that can use an emerging safety-certification pathway via the Zephyr Safety Working Group
- Teams preferring modern build systems (CMake, Devicetree, Kconfig)
- Long-term product lines requiring vendor-agnostic hardware portability
Market Context
The embedded RTOS market, valued at approximately $1.8 billion in 2024, continues its trajectory toward $3.2 billion by 2030, driven by Industrial IoT adoption, automotive electrification, and consumer wearables proliferation. Within this market, FreeRTOS maintains approximately 38% deployment share among surveyed embedded developers, while Zephyr has grown from negligible presence in 2017 to approximately 18% in 2024, representing the fastest growth rate among all RTOS platforms.
Recommendations Summary
Organizations should select FreeRTOS when working with resource-constrained devices (especially under 32KB flash / 8KB RAM), requiring AWS cloud integration, or needing minimal learning curve for teams transitioning from bare-metal development.
Organizations should select Zephyr when building products requiring multi-protocol wireless connectivity, anticipating hardware platform changes, or seeking modern DevOps-friendly development workflows.
This document provides the technical depth required for informed decision-making, including architecture analysis, benchmark comparisons, code examples, migration strategies, and a comprehensive decision framework applicable to diverse embedded system requirements.
Chapter 1: The 2025 RTOS Landscape and Market Dynamics
1.1 Market Overview and Size
The global Real-Time Operating System market has experienced sustained growth throughout the early 2020s, driven by the proliferation of connected devices, industrial automation initiatives, and the expanding Internet of Things ecosystem. According to industry analyses from Grand View Research and Markets and Markets, the RTOS market reached an estimated valuation of $1.81 billion in 2024, with projections indicating growth to $3.24 billion by 2030, representing a compound annual growth rate (CAGR) of 10.2%.
This growth is not uniformly distributed across all RTOS categories. Commercial RTOS solutions, including Wind River VxWorks, Green Hills INTEGRITY, and BlackBerry QNX, continue to dominate safety-critical applications in aerospace, defense, and automotive sectors, commanding premium pricing justified by extensive certification artifacts and long-term support guarantees. However, open-source alternatives have captured the majority of new embedded project starts, particularly in consumer IoT, industrial sensors, and connected consumer electronics.
| Market Segment | 2024 Value | 2030 Projection | Primary RTOS Choices |
|---|---|---|---|
| Consumer IoT | $412M | $892M | FreeRTOS, Zephyr, ESP-IDF |
| Industrial IoT | $521M | $978M | FreeRTOS, Zephyr, ThreadX |
| Automotive | $298M | $612M | QNX, AUTOSAR, Zephyr |
| Aerospace/Defense | $287M | $398M | VxWorks, INTEGRITY, LynxOS |
| Medical Devices | $156M | $298M | QNX, FreeRTOS, Zephyr |
| Others | $136M | $262M | Various |
Developer surveys consistently show FreeRTOS as the most widely deployed RTOS globally. The 2024 Embedded Market Study conducted by Aspencore revealed that 38% of embedded developers reported using FreeRTOS in their most recent project, followed by proprietary/custom RTOSes at 22%, Zephyr at 18%, and various commercial options comprising the remainder. Notably, Zephyr’s growth trajectory has been remarkable, increasing from 4% adoption in 2019 to 18% in 2024, representing the fastest growth rate among all tracked RTOS platforms.
1.2 Key Industry Trends
Several macro-level trends are reshaping RTOS selection criteria and driving the evolution of both FreeRTOS and Zephyr:
Edge Computing and AI Integration
The migration of computational workloads from cloud to edge has created demand for RTOSes capable of supporting machine learning inference frameworks. Both FreeRTOS and Zephyr have responded to this trend, though with different approaches. FreeRTOS maintains its lightweight philosophy, offering integration with Amazon’s TinyML-compatible frameworks and supporting external accelerators through standard peripheral interfaces. Zephyr has taken a more integrated approach, incorporating TensorFlow Lite Micro support directly into its build system and providing optimized kernels for neural network operations on supported hardware.
Security as a First-Class Requirement
The increasing frequency and sophistication of attacks targeting embedded devices has elevated security from afterthought to primary design consideration. Modern RTOS selection now routinely includes evaluation of secure boot chains, cryptographic library integration, secure element support, and over-the-air update capabilities. FreeRTOS addresses these requirements through its separately licensed FreeRTOS+TCP, coreMQTT, and AWS IoT device libraries, while Zephyr incorporates PSA (Platform Security Architecture) certified implementations and MCUboot integration as standard components.
Wireless Protocol Proliferation
The embedded wireless landscape has grown increasingly complex, with devices now routinely required to support multiple protocols including Bluetooth Low Energy, Thread, Zigbee, Wi-Fi, LoRaWAN, and the emerging Matter standard. This multi-protocol requirement has significant implications for RTOS selection, as protocol stack quality and integration depth vary substantially between platforms. Zephyr has emerged as a leader in this dimension, offering certified Bluetooth 5.3 and Thread 1.3 stacks developed in collaboration with Nordic Semiconductor, while FreeRTOS typically relies on vendor-specific implementations or third-party stacks.
Safety Certification Democratization
Historically, safety certification for embedded software required either commercial RTOS licenses costing hundreds of thousands of dollars or expensive custom certification efforts. The emergence of pre-certified RTOS components and certification-ready configurations has begun democratizing access to safety-critical markets. SAFERTOS, a commercially licensed derivative of FreeRTOS, offers IEC 61508 SIL 3 and ISO 26262 ASIL D pre-certification. The Zephyr project is working toward IEC 61508 SIL 3 certification of an auditable kernel subset built on its Long Term Support (LTS) releases.
Industry Insight
According to the 2024 IoT Signals report from Microsoft and Hypothesis Group, 43% of IoT decision-makers cite “lack of necessary talent/resources” as a primary adoption barrier. RTOS selection directly impacts this challenge, as platforms with stronger ecosystems, better documentation, and more available training resources reduce the talent acquisition burden.
1.3 Major RTOS Players
Understanding the competitive landscape helps contextualize the FreeRTOS versus Zephyr decision within the broader market:
FreeRTOS (Amazon Web Services)
Originally developed by Richard Barry and Real Time Engineers Ltd., FreeRTOS was acquired by Amazon in 2017. The acquisition brought significant investment in cloud integration, security libraries, and long-term support guarantees. FreeRTOS is distributed under the MIT license, ensuring maximum flexibility for commercial deployment without royalty obligations. The kernel has been downloaded over 185,000 times per year according to SourceForge statistics, and AWS estimates deployment in over 40 billion devices worldwide.
Zephyr (Linux Foundation)
Launched in 2016 as a Linux Foundation Collaborative Project, Zephyr has rapidly evolved from experimental platform to production-ready RTOS. Platinum members contributing to Zephyr development include Intel, Nordic Semiconductor, NXP, Texas Instruments, and Google. The project maintains an aggressive release cadence, with major versions every four months and LTS releases roughly every two years (latest 3.7 LTS, July 2024). Zephyr is licensed under Apache 2.0, providing similar commercial flexibility to FreeRTOS’s MIT license.
ThreadX (Microsoft/Eclipse Foundation)
Microsoft acquired ThreadX developer Express Logic in 2019, subsequently contributing the RTOS to the Eclipse Foundation as Eclipse ThreadX in 2023. ThreadX offers an interesting middle ground between FreeRTOS and Zephyr, with more features than FreeRTOS but a smaller footprint than Zephyr. Its transition to open source is still maturing, and ecosystem momentum lags behind both FreeRTOS and Zephyr.
Commercial Options
Wind River VxWorks, Green Hills INTEGRITY, and BlackBerry QNX remain the choices for the most demanding safety-critical applications. VxWorks commands the aerospace and defense markets, INTEGRITY dominates high-security applications requiring separation kernel architecture, and QNX maintains strong positions in automotive infotainment and medical devices. These platforms typically cost $15,000-$50,000+ per product line in licensing fees, justified by decades of certification heritage and comprehensive support infrastructure.
1.4 Open Source vs Commercial Trade-offs
The decision between open-source RTOSes (FreeRTOS, Zephyr) and commercial alternatives involves trade-offs across multiple dimensions:
| Dimension | Open Source (FreeRTOS/Zephyr) | Commercial (VxWorks/QNX/INTEGRITY) |
|---|---|---|
| Licensing Cost | $0 (MIT/Apache 2.0) | $15,000 - $250,000+ per product |
| Support Model | Community + optional commercial | Dedicated engineering support |
| Certification Heritage | Emerging (Zephyr LTS, SAFERTOS) | Decades of certification history |
| Documentation Quality | Variable, improving | Comprehensive, professional |
| Ecosystem Breadth | Extensive, community-driven | Curated, vendor-supported |
| Long-term Viability | Strong (major corporate backing) | Dependent on vendor health |
| Customization Flexibility | Complete source access | Often limited to APIs |
For the majority of embedded projects outside safety-critical domains, open-source RTOSes now provide equivalent or superior capabilities at dramatically lower total cost of ownership. The remaining sections of this white paper focus exclusively on the FreeRTOS versus Zephyr decision, as these two platforms represent the most viable options for the broadest range of embedded applications in 2025.
Chapter 2: FreeRTOS Deep Dive
2.1 Historical Context and Evolution
FreeRTOS traces its origins to 2003 when Richard Barry created the kernel as a lightweight, portable RTOS designed specifically for microcontrollers. The initial release targeted the ARM7 architecture and was distributed under a modified GPL license that permitted linking with proprietary code without viral licensing implications. This permissive approach proved instrumental in FreeRTOS’s widespread adoption, as embedded developers could incorporate the kernel into commercial products without legal complexity.
The project evolved steadily throughout the 2000s and early 2010s, with Barry maintaining the kernel through his company, Real Time Engineers Ltd. During this period, FreeRTOS established several characteristics that remain defining features today: minimal code footprint, deterministic scheduling behavior, and extensive portability across microcontroller architectures. By 2017, FreeRTOS had accumulated deployment in billions of devices and established itself as the de facto standard for resource-constrained embedded systems.
Amazon’s acquisition of FreeRTOS in November 2017 marked a transformational moment. AWS invested significantly in the project, transitioning the license to MIT (eliminating all restrictions), developing the FreeRTOS+AWS IoT integration libraries, and establishing the Amazon FreeRTOS distribution that bundles the kernel with security libraries, TCP/IP stack, and cloud connectivity components. This investment accelerated feature development while maintaining backward compatibility with existing deployments.
Version History Highlights
FreeRTOS V10.0.0 (2017): MIT license adoption, AWS acquisition
FreeRTOS V10.4.0 (2020): Multiple task notifications per task
FreeRTOS V10.5.0 (2022): Enhanced memory protection unit integration
FreeRTOS V11.0.0 (Dec 2023): SMP support merged into mainline; ARMv8-M improvements
2.2 Kernel Architecture
FreeRTOS implements a preemptive priority-based scheduler as its core scheduling mechanism. The kernel maintains a ready list for each priority level, with higher priority tasks always preempting lower priority tasks when they become ready to execute. This design ensures predictable, deterministic behavior essential for real-time applications while remaining simple enough for developers to understand and debug.
Task States and Transitions
FreeRTOS tasks exist in one of four states at any given time:
- Running: The task is currently executing on the processor. Only one task can be in this state per processor core.
- Ready: The task is able to execute but is not currently running because a task of equal or higher priority is running.
- Blocked: The task is waiting for an event (timer expiration, semaphore availability, queue message, etc.) and cannot execute.
- Suspended: The task has been explicitly suspended via
vTaskSuspend()and will not execute until resumed.
┌─────────────────────────────────────────────────────────────────────┐
│ FreeRTOS Task State Diagram │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────┐ │
│ │ RUNNING │ │
│ └────┬─────┘ │
│ ┌───────────┼───────────┐ │
│ │ │ │ │
│ preempt/yield block suspend │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌─────────┐ ┌─────────┐ ┌───────────┐ │
│ │ READY │ │ BLOCKED │ │ SUSPENDED │ │
│ └────┬────┘ └────┬────┘ └─────┬─────┘ │
│ │ │ │ │
│ schedule event/timeout resume │
│ │ │ │ │
│ └────────────┴─────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────┐ │
│ │ RUNNING │ │
│ └──────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────┘
Figure 2.1: FreeRTOS task state transitions
Task Creation Example
The following code demonstrates FreeRTOS task creation with proper error handling:
/* FreeRTOS Task Creation Example */
#include "FreeRTOS.h"
#include "task.h"
/* Task handle for reference */
TaskHandle_t sensorTaskHandle = NULL;
/* Task function prototype */
void vSensorTask(void *pvParameters);
/* Task implementation */
void vSensorTask(void *pvParameters)
{
TickType_t xLastWakeTime;
const TickType_t xFrequency = pdMS_TO_TICKS(100); /* 100ms period */
/* Initialize the xLastWakeTime variable with current time */
xLastWakeTime = xTaskGetTickCount();
for(;;)
{
/* Read sensor data */
int16_t temperature = readTemperatureSensor();
int16_t humidity = readHumiditySensor();
/* Process and transmit data */
processSensorData(temperature, humidity);
/* Wait for the next cycle - maintains precise timing */
vTaskDelayUntil(&xLastWakeTime, xFrequency);
}
}
/* Create the task in main() or initialization function */
void initializeTasks(void)
{
BaseType_t xReturned;
xReturned = xTaskCreate(
vSensorTask, /* Task function */
"SensorTask", /* Task name for debugging */
configMINIMAL_STACK_SIZE + 128, /* Stack size in words */
NULL, /* Parameters to pass */
tskIDLE_PRIORITY + 2, /* Priority */
&sensorTaskHandle /* Task handle */
);
if(xReturned != pdPASS)
{
/* Handle task creation failure */
configASSERT(0);
}
}
Scheduler Implementation
The FreeRTOS scheduler operates through the vTaskSwitchContext() function, which is invoked either by the SysTick interrupt handler (for time-slicing and blocked task management) or by API calls that may cause a context switch. The scheduler algorithm is straightforward: select the highest priority task from the ready lists that is able to run. When multiple tasks share the same priority, round-robin scheduling distributes processor time equally among them.
The tick interrupt frequency, typically configured between 100Hz and 1000Hz, determines the temporal granularity of the scheduler. Higher tick rates provide finer timing resolution but increase overhead. For most applications, 1000Hz (1ms tick) provides an appropriate balance between responsiveness and efficiency.
2.3 Memory Management Schemes
FreeRTOS provides five heap management implementations, allowing developers to select the scheme most appropriate for their application’s memory allocation patterns:
| Heap Implementation | Allocation | Deallocation | Best Use Case |
|---|---|---|---|
| heap_1.c | Yes | No | Static systems where tasks/queues created once at startup |
| heap_2.c | Yes | Yes (no coalescing) | Applications allocating same-size blocks repeatedly |
| heap_3.c | Yes (wraps malloc) | Yes (wraps free) | Systems with thread-safe malloc implementation |
| heap_4.c | Yes | Yes (with coalescing) | General purpose - recommended default |
| heap_5.c | Yes | Yes (with coalescing) | Non-contiguous memory regions (multiple RAM banks) |
The heap_4.c implementation represents the recommended choice for most applications. It implements a first-fit algorithm with adjacent free block coalescing, providing efficient memory utilization while avoiding fragmentation issues that plague naive allocators. Memory is allocated from a statically declared array, ucHeap, whose size is configured via configTOTAL_HEAP_SIZE in FreeRTOSConfig.h.
/* FreeRTOSConfig.h memory configuration */
#define configTOTAL_HEAP_SIZE ((size_t)(32 * 1024)) /* 32KB heap */
#define configAPPLICATION_ALLOCATED_HEAP 0 /* Let FreeRTOS allocate */
/* Memory allocation failure hook (optional but recommended) */
#define configUSE_MALLOC_FAILED_HOOK 1
/* Hook implementation */
void vApplicationMallocFailedHook(void)
{
/* Called when pvPortMalloc() fails */
taskDISABLE_INTERRUPTS();
for(;;); /* Halt in debug builds */
}
Memory Management Best Practice
For safety-critical applications, avoid dynamic memory allocation after initialization. Create all tasks, queues, semaphores, and timers during startup using static allocation variants (
xTaskCreateStatic(),xQueueCreateStatic(), etc.) to ensure deterministic memory usage and eliminate allocation failure scenarios during runtime.
2.4 ESP32 and STM32 Integration
FreeRTOS enjoys first-class support on the two most popular microcontroller families for IoT development: Espressif’s ESP32 series and STMicroelectronics’ STM32 family.
ESP32 Integration (ESP-IDF)
Espressif’s ESP-IDF (IoT Development Framework) is built upon a modified FreeRTOS kernel optimized for the ESP32’s dual-core Xtensa LX6/LX7 architecture. ESP-IDF extends standard FreeRTOS with symmetric multiprocessing (SMP) support, allowing tasks to execute on either core and providing mechanisms for core affinity when needed.
/* ESP32-specific task creation with core affinity */
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
static const char *TAG = "main";
void wifi_task(void *pvParameters)
{
while(1) {
/* WiFi processing - runs on Core 0 */
ESP_LOGI(TAG, "WiFi task running on core %d", xPortGetCoreID());
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void sensor_task(void *pvParameters)
{
while(1) {
/* Sensor processing - runs on Core 1 */
ESP_LOGI(TAG, "Sensor task running on core %d", xPortGetCoreID());
vTaskDelay(pdMS_TO_TICKS(100));
}
}
void app_main(void)
{
/* Pin WiFi task to Core 0 (where WiFi driver runs) */
xTaskCreatePinnedToCore(
wifi_task,
"wifi_task",
4096,
NULL,
5,
NULL,
0 /* Core 0 */
);
/* Pin sensor task to Core 1 for isolation */
xTaskCreatePinnedToCore(
sensor_task,
"sensor_task",
2048,
NULL,
10,
NULL,
1 /* Core 1 */
);
}
STM32 Integration (STM32CubeMX)
STMicroelectronics provides FreeRTOS integration through the STM32CubeMX code generation tool and the CMSIS-RTOS2 abstraction layer. This integration allows developers to configure FreeRTOS parameters graphically and generate initialization code automatically.
/* STM32CubeIDE generated FreeRTOS initialization */
#include "cmsis_os.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
/* Definitions for defaultTask */
osThreadId_t defaultTaskHandle;
const osThreadAttr_t defaultTask_attributes = {
.name = "defaultTask",
.stack_size = 128 * 4,
.priority = (osPriority_t) osPriorityNormal,
};
/* Definitions for LED task */
osThreadId_t ledTaskHandle;
const osThreadAttr_t ledTask_attributes = {
.name = "ledTask",
.stack_size = 128 * 4,
.priority = (osPriority_t) osPriorityLow,
};
void StartDefaultTask(void *argument)
{
for(;;)
{
/* Main application logic */
HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
osDelay(500);
}
}
void MX_FREERTOS_Init(void)
{
/* Create tasks using CMSIS-RTOS2 API */
defaultTaskHandle = osThreadNew(StartDefaultTask, NULL,
&defaultTask_attributes);
ledTaskHandle = osThreadNew(StartLEDTask, NULL,
&ledTask_attributes);
}
2.5 AWS IoT Integration
Amazon’s investment in FreeRTOS has produced a comprehensive suite of libraries for AWS IoT Core connectivity. The AWS IoT Device SDK for Embedded C provides production-ready implementations of MQTT, HTTP, and device shadow protocols, all designed for resource-constrained environments.
Core Components
The AWS FreeRTOS distribution includes several key components:
- coreMQTT: Lightweight MQTT 3.1.1 client optimized for embedded systems
- coreHTTP: HTTP/1.1 client for REST API communication
- coreJSON: JSON parser designed for memory-constrained devices
- corePKCS11: PKCS#11 implementation for secure key storage
- Device Shadow: Local state synchronization with AWS IoT Thing Shadows
- Device Defender: Security monitoring and anomaly detection
- OTA Update Agent: Over-the-air firmware update capability
/* AWS IoT Core MQTT Connection Example */
#include "core_mqtt.h"
#include "core_mqtt_agent.h"
#include "transport_secure_sockets.h"
#define AWS_IOT_ENDPOINT "xxxxx.iot.us-west-2.amazonaws.com"
#define AWS_IOT_PORT 8883
#define CLIENT_IDENTIFIER "freertos-device-001"
static MQTTContext_t mqttContext;
static NetworkContext_t networkContext;
static uint8_t mqttBuffer[1024];
MQTTStatus_t connectToAwsIot(void)
{
MQTTStatus_t mqttStatus;
MQTTConnectInfo_t connectInfo = { 0 };
TransportInterface_t transport;
MQTTFixedBuffer_t fixedBuffer;
bool sessionPresent;
/* Configure TLS transport */
SecureSocketsTransport_Connect(&networkContext,
AWS_IOT_ENDPOINT,
AWS_IOT_PORT,
&tlsCredentials);
/* Set up transport interface */
transport.pNetworkContext = &networkContext;
transport.send = SecureSocketsTransport_Send;
transport.recv = SecureSocketsTransport_Recv;
/* Initialize MQTT context */
fixedBuffer.pBuffer = mqttBuffer;
fixedBuffer.size = sizeof(mqttBuffer);
mqttStatus = MQTT_Init(&mqttContext, &transport,
Clock_GetTimeMs, eventCallback, &fixedBuffer);
if(mqttStatus == MQTTSuccess)
{
/* Configure connection parameters */
connectInfo.cleanSession = true;
connectInfo.pClientIdentifier = CLIENT_IDENTIFIER;
connectInfo.clientIdentifierLength = strlen(CLIENT_IDENTIFIER);
connectInfo.keepAliveSeconds = 60;
/* Establish MQTT connection */
mqttStatus = MQTT_Connect(&mqttContext, &connectInfo,
NULL, 5000, &sessionPresent);
}
return mqttStatus;
}
/* Publish sensor data to AWS IoT */
MQTTStatus_t publishSensorData(float temperature, float humidity)
{
MQTTPublishInfo_t publishInfo = { 0 };
char payload[128];
/* Format JSON payload */
snprintf(payload, sizeof(payload),
"{\"temperature\":%.2f,\"humidity\":%.2f,\"timestamp\":%lu}",
temperature, humidity, (unsigned long)time(NULL));
/* Configure publish parameters */
publishInfo.qos = MQTTQoS1;
publishInfo.pTopicName = "sensors/device-001/data";
publishInfo.topicNameLength = strlen(publishInfo.pTopicName);
publishInfo.pPayload = payload;
publishInfo.payloadLength = strlen(payload);
return MQTT_Publish(&mqttContext, &publishInfo,
MQTT_GetPacketId(&mqttContext));
}
AWS IoT Qualification Program
Amazon maintains the AWS IoT Device Qualification Program, which provides pre-tested reference implementations for specific microcontroller platforms. Qualified devices include the ESP32, STM32, NXP i.MX RT series, and Infineon PSoC 6, among others. Using qualified reference implementations significantly accelerates time-to-cloud connectivity.
Chapter 3: Zephyr Deep Dive
3.1 Linux Foundation Governance
Zephyr operates under the governance of the Linux Foundation, the same organization that stewards the Linux kernel, Kubernetes, and numerous other critical open-source infrastructure projects. This governance model provides several advantages that distinguish Zephyr from both FreeRTOS and proprietary alternatives.
The Zephyr Project was established in February 2016 with founding members including Intel, NXP, Synopsys, and Linaro. The project adopted the Apache 2.0 license, which permits commercial use, modification, and distribution without copyleft requirements while providing explicit patent grants. This licensing choice removes legal uncertainty that sometimes accompanies open-source adoption in commercial products.
Governance Structure
The project operates through a multi-tiered governance structure:
- Governing Board: Comprises representatives from Platinum and Gold member organizations, responsible for strategic direction, budget allocation, and membership policies.
- Technical Steering Committee (TSC): Oversees technical roadmap, architecture decisions, release planning, and working group coordination.
- Working Groups: Focused teams addressing specific domains including Architecture, API, Bluetooth, Safety, and CI/Testing.
- Maintainers: Individual contributors with merge authority for specific subsystems, selected based on demonstrated expertise and contribution history.
Current Platinum members include Intel, Nordic Semiconductor, NXP, Google, Meta, and Texas Instruments. Each Platinum member contributes significant engineering resources to the project, typically multiple full-time developers dedicated to Zephyr development. This corporate investment ensures sustained development velocity and long-term project viability.
Release Cadence
Zephyr follows a predictable release schedule: major releases every four months (typically February, June, October) with Long Term Support (LTS) releases roughly every two years (latest 3.7 LTS, July 2024). LTS releases receive security updates and critical bug fixes for two years, providing stability guarantees essential for product development cycles.
3.2 Architecture Overview
Zephyr’s architecture reflects its origins as a modern RTOS designed with hindsight from decades of embedded operating system evolution. The kernel provides a comprehensive set of services while maintaining configurability that allows unnecessary components to be excluded from the final binary.
Kernel Services
The Zephyr kernel provides the following core services:
- Threads: Preemptive and cooperative scheduling with priority inheritance, thread-local storage, and user/kernel mode separation on supported architectures.
- Scheduling: Multiple schedulers available including simple priority-based, round-robin, earliest deadline first (EDF), and multi-queue.
- Synchronization: Mutexes, semaphores, condition variables, and futex-like primitives.
- Data Passing: FIFOs, LIFOs, message queues, mailboxes, and pipes for inter-thread communication.
- Memory Management: Kernel heap, memory pools, memory slabs, and optional memory protection unit (MPU) support.
- Timing: Kernel timers, system clock, busy-wait delays, and tickless operation support.
┌──────────────────────────────────────────────────────────────────────────┐
│ Zephyr Architecture │
├──────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ Application Layer │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ │
│ │ │ Threads │ │ Sensors │ │ Network │ │ User Libraries │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ OS Services Layer │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ │
│ │ │Bluetooth │ │ WiFi │ │ Thread/ │ │ File Systems │ │ │
│ │ │ Stack │ │ Stack │ │ Matter │ │ (LittleFS, FAT) │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ │
│ │ │ Logging │ │ Shell │ │ POSIX │ │ MCUboot │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ Kernel Layer │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ │
│ │ │Scheduler │ │ Memory │ │ IPC │ │ Timing/Timers │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ Hardware Abstraction Layer │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ │
│ │ │ GPIO │ │ I2C │ │ SPI │ │ UART/USB │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ Architecture Support (ARM, RISC-V, x86, etc.) │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────┘
Figure 3.1: Zephyr layered architecture
Thread Creation Example
Zephyr provides both dynamic and static thread creation. The static approach is preferred for deterministic memory usage:
/* Zephyr Thread Creation Example */
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(sensor_task, LOG_LEVEL_INF);
/* Define thread stack and data statically */
#define SENSOR_STACK_SIZE 1024
#define SENSOR_PRIORITY 5
K_THREAD_STACK_DEFINE(sensor_stack, SENSOR_STACK_SIZE);
struct k_thread sensor_thread_data;
/* Thread entry point */
void sensor_thread_entry(void *p1, void *p2, void *p3)
{
int64_t next_wakeup = k_uptime_get();
while (1) {
/* Read sensor data */
int16_t temperature = read_temperature_sensor();
int16_t humidity = read_humidity_sensor();
LOG_INF("Temp: %d.%02d C, Humidity: %d.%02d %%",
temperature / 100, temperature % 100,
humidity / 100, humidity % 100);
/* Process data */
process_sensor_data(temperature, humidity);
/* Sleep until next 100ms interval (precise timing) */
next_wakeup += 100; /* 100ms period */
k_sleep(K_TIMEOUT_ABS_MS(next_wakeup));
}
}
/* Initialize and start the thread */
void start_sensor_thread(void)
{
k_tid_t tid = k_thread_create(
&sensor_thread_data,
sensor_stack,
SENSOR_STACK_SIZE,
sensor_thread_entry,
NULL, NULL, NULL,
SENSOR_PRIORITY,
0, /* Options */
K_NO_WAIT /* Start immediately */
);
k_thread_name_set(tid, "sensor_thread");
}
/* Alternative: Define thread at compile time using macro */
K_THREAD_DEFINE(my_thread, 1024,
sensor_thread_entry, NULL, NULL, NULL,
SENSOR_PRIORITY, 0, 0);
3.3 Devicetree and Kconfig System
One of Zephyr’s most distinctive features is its adoption of Devicetree and Kconfig, configuration systems borrowed from the Linux kernel. These systems enable powerful hardware abstraction and build-time configuration that separate hardware details from application logic.
Devicetree Overview
Devicetree is a data structure that describes hardware components to the operating system. In Zephyr, devicetree files (.dts and .dtsi) describe the board’s peripherals, pin assignments, and hardware parameters. The build system processes these files and generates C header files that application code uses to interact with hardware.
/* Example Devicetree source (boards/myboard/myboard.dts) */
/dts-v1/;
#include <nordic/nrf52840_qiaa.dtsi>
#include "myboard-pinctrl.dtsi"
/ {
model = "My Custom Board";
compatible = "mycompany,myboard";
chosen {
zephyr,console = &uart0;
zephyr,shell-uart = &uart0;
zephyr,sram = &sram0;
zephyr,flash = &flash0;
};
leds {
compatible = "gpio-leds";
led0: led_0 {
gpios = <&gpio0 13 GPIO_ACTIVE_LOW>;
label = "Green LED";
};
led1: led_1 {
gpios = <&gpio0 14 GPIO_ACTIVE_LOW>;
label = "Red LED";
};
};
buttons {
compatible = "gpio-keys";
button0: button_0 {
gpios = <&gpio0 11 (GPIO_PULL_UP | GPIO_ACTIVE_LOW)>;
label = "Push button 1";
};
};
aliases {
led0 = &led0;
led1 = &led1;
sw0 = &button0;
i2c-sensors = &i2c0;
};
};
&i2c0 {
compatible = "nordic,nrf-twim";
status = "okay";
pinctrl-0 = <&i2c0_default>;
pinctrl-1 = <&i2c0_sleep>;
pinctrl-names = "default", "sleep";
clock-frequency = <I2C_BITRATE_FAST>;
bme280@76 {
compatible = "bosch,bme280";
reg = <0x76>;
label = "BME280";
};
};
&uart0 {
status = "okay";
current-speed = <115200>;
pinctrl-0 = <&uart0_default>;
pinctrl-1 = <&uart0_sleep>;
pinctrl-names = "default", "sleep";
};
Kconfig System
Kconfig provides compile-time configuration for software components. Each Zephyr module defines its configuration options in Kconfig files, and projects specify their selections in prj.conf.
# Project configuration file (prj.conf)
# Kernel configuration
CONFIG_MAIN_STACK_SIZE=2048
CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=2048
CONFIG_HEAP_MEM_POOL_SIZE=16384
# Logging
CONFIG_LOG=y
CONFIG_LOG_MODE_DEFERRED=y
CONFIG_LOG_BUFFER_SIZE=4096
# Bluetooth configuration
CONFIG_BT=y
CONFIG_BT_PERIPHERAL=y
CONFIG_BT_DEVICE_NAME="My Sensor"
CONFIG_BT_DEVICE_APPEARANCE=833
CONFIG_BT_MAX_CONN=2
CONFIG_BT_MAX_PAIRED=2
# Sensor subsystem
CONFIG_SENSOR=y
CONFIG_BME280=y
# Networking (for Thread/Matter)
CONFIG_NETWORKING=y
CONFIG_NET_IPV6=y
CONFIG_NET_UDP=y
# Shell for debugging
CONFIG_SHELL=y
CONFIG_SHELL_BACKEND_SERIAL=y
Using Devicetree in Application Code
/* Accessing hardware through Devicetree */
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/sensor.h>
/* Get LED device from devicetree alias */
#define LED0_NODE DT_ALIAS(led0)
static const struct gpio_dt_spec led =
GPIO_DT_SPEC_GET(LED0_NODE, gpios);
/* Get sensor device */
static const struct device *bme280 =
DEVICE_DT_GET_ONE(bosch_bme280);
int main(void)
{
struct sensor_value temp, humidity, pressure;
int ret;
/* Verify devices are ready */
if (!gpio_is_ready_dt(&led)) {
return -ENODEV;
}
if (!device_is_ready(bme280)) {
return -ENODEV;
}
/* Configure LED GPIO */
ret = gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
if (ret < 0) {
return ret;
}
while (1) {
/* Toggle LED */
gpio_pin_toggle_dt(&led);
/* Read sensor */
sensor_sample_fetch(bme280);
sensor_channel_get(bme280, SENSOR_CHAN_AMBIENT_TEMP, &temp);
sensor_channel_get(bme280, SENSOR_CHAN_HUMIDITY, &humidity);
sensor_channel_get(bme280, SENSOR_CHAN_PRESS, &pressure);
printk("T: %d.%06d; H: %d.%06d; P: %d.%06d\n",
temp.val1, temp.val2,
humidity.val1, humidity.val2,
pressure.val1, pressure.val2);
k_sleep(K_SECONDS(1));
}
return 0;
}
3.4 Board Support and HAL
Zephyr’s extensive board support represents one of its strongest competitive advantages. As of version 3.7 LTS (2024), Zephyr supports over 600 boards from more than 50 silicon vendors, spanning architectures including ARM Cortex-M, ARM Cortex-A, RISC-V, x86, Xtensa, ARC, and SPARC.
Hardware Abstraction Layer
Zephyr’s HAL provides consistent APIs across different hardware platforms. The driver model follows a standardized structure where each driver type (GPIO, SPI, I2C, UART, etc.) implements a common API defined by the kernel.
| Architecture | Notable Platforms | Board Count |
|---|---|---|
| ARM Cortex-M | STM32, nRF52/53, NXP LPC/i.MX RT, Microchip SAM | 450+ |
| ARM Cortex-A | Raspberry Pi, i.MX 8, Xilinx Zynq | 30+ |
| RISC-V | SiFive, ESP32-C3/C6, GigaDevice GD32V | 80+ |
| Xtensa | ESP32, ESP32-S2/S3 | 20+ |
| x86 | Intel Quark, Apollo Lake, QEMU | 15+ |
| ARC | Synopsys ARC EM/HS | 10+ |
3.5 Nordic and Intel Ecosystem
Nordic Semiconductor and Intel represent Zephyr’s most significant ecosystem partners, contributing substantial engineering resources and treating Zephyr as their primary RTOS for next-generation products.
Nordic Semiconductor
Nordic has adopted Zephyr as the official RTOS for its nRF Connect SDK, replacing their proprietary nRF5 SDK. All current Nordic development for nRF52, nRF53, and nRF91 series targets the Zephyr-based nRF Connect SDK, making Zephyr the default choice for one of the most popular Bluetooth and cellular IoT chip families.
Nordic’s Bluetooth stack in Zephyr is particularly noteworthy, offering Bluetooth 5.3 compliance with features including:
- LE Audio with LC3 codec support
- Direction finding (AoA/AoD)
- Extended advertising
- Periodic advertising sync transfer
- Multiple PHY support (1M, 2M, Coded)
- Connection-oriented channels (L2CAP CoC)
Intel
As a founding member, Intel has integrated Zephyr into its embedded processor ecosystem, particularly for IoT gateway applications and edge computing platforms. Intel’s contributions focus on x86 architecture support, device management integration, and enterprise connectivity features.
Ecosystem Advantage
When selecting Nordic nRF series or Intel embedded platforms, choosing Zephyr provides optimal vendor support, fastest access to new silicon features, and alignment with the chip vendor’s recommended development practices. For these platforms specifically, Zephyr often represents the path of least resistance rather than an alternative requiring justification.
Chapter 4: Performance Benchmarks
Performance characteristics represent a critical differentiator between RTOS platforms, particularly for applications with stringent timing requirements or severe resource constraints. This chapter presents illustrative figures compiled from published benchmarks and vendor documentation (not a Rapid Circuitry bench study), with a reference method for reproducing the measurements on your own hardware.
4.1 Memory Footprint Analysis
Memory consumption directly impacts bill-of-materials cost, as smaller firmware images enable selection of less expensive microcontrollers with reduced Flash and RAM. Both FreeRTOS and Zephyr offer extensive configurability, making apples-to-apples comparison challenging. The following benchmarks establish comparable configurations for meaningful comparison.
Minimal Kernel Configuration
The absolute minimum configuration includes only kernel scheduling, one task beyond idle, and no additional services:
| Configuration | FreeRTOS | Zephyr | Notes |
|---|---|---|---|
| Minimal Kernel (Flash) | 4.8 KB | 8.2 KB | Cortex-M4, GCC -Os |
| Minimal Kernel (RAM) | 1.1 KB | 2.4 KB | Single task + idle |
| + Timers | +0.8 KB / +0.3 KB | +1.2 KB / +0.4 KB | Software timer support |
| + Queues | +0.6 KB / +0.2 KB | +0.9 KB / +0.3 KB | Message queue primitives |
| + Semaphores/Mutexes | +0.4 KB / +0.1 KB | +0.7 KB / +0.2 KB | Synchronization primitives |
Typical IoT Application Configuration
A more realistic comparison examines configurations suitable for typical IoT sensor applications including GPIO, I2C sensor driver, timer, and basic logging:
| Component | FreeRTOS + HAL | Zephyr |
|---|---|---|
| Kernel + Scheduler | 5.2 KB | 9.1 KB |
| GPIO Driver | 1.8 KB (vendor HAL) | 2.4 KB |
| I2C Driver | 2.2 KB (vendor HAL) | 3.1 KB |
| Timer Subsystem | 0.8 KB | 1.4 KB |
| Logging (minimal) | 1.2 KB (custom) | 4.8 KB |
| Total Flash | 11.2 KB | 20.8 KB |
| Total RAM | 3.8 KB | 6.2 KB |
Full-Featured IoT Configuration
For applications requiring Bluetooth Low Energy connectivity, the comparison shifts significantly:
| Component | FreeRTOS + NimBLE | Zephyr (integrated) |
|---|---|---|
| Kernel + Services | 12.4 KB | 18.2 KB |
| BLE Stack | 68.5 KB | 72.1 KB |
| BLE Profiles (GATT, GAP) | 8.2 KB | 9.4 KB |
| Crypto (mbedTLS) | 42.3 KB | 44.8 KB |
| Shell/Console | 6.8 KB | 12.4 KB |
| Total Flash | 138.2 KB | 156.9 KB |
| Total RAM | 28.4 KB | 34.2 KB |
Memory Analysis Insight
FreeRTOS maintains a consistent 15-25% memory advantage across configurations. However, this advantage narrows for feature-rich applications where protocol stacks dominate memory consumption. For applications requiring 256KB+ Flash, the memory difference becomes negligible relative to total firmware size.
4.2 Context Switch Performance
Context switch time measures the duration required to save one task’s state and restore another’s. This metric directly impacts system responsiveness and overhead for multi-task applications.
Benchmark Methodology
Context switch measurements used the following approach:
- Two equal-priority tasks ping-pong using binary semaphore
- GPIO toggle at switch points for oscilloscope measurement
- 1000 iterations averaged to eliminate cache effects
- Other interrupts masked during measurement; PendSV and SysTick left enabled
| Platform | Clock Speed | FreeRTOS | Zephyr |
|---|---|---|---|
| STM32F407 (Cortex-M4) | 168 MHz | 2.1 us | 2.8 us |
| nRF52840 (Cortex-M4F) | 64 MHz | 4.8 us | 6.2 us |
| ESP32 (Xtensa LX6) | 240 MHz | 1.9 us | 2.4 us |
| NXP i.MX RT1060 (Cortex-M7) | 600 MHz | 0.8 us | 1.1 us |
| STM32L476 (Cortex-M4) | 80 MHz | 3.2 us | 4.4 us |
FreeRTOS demonstrates 25-35% faster context switches across tested platforms. This advantage stems from FreeRTOS’s simpler task control block structure and streamlined scheduler implementation. However, absolute differences of 1-2 microseconds are immaterial for most applications where task switch frequency remains below 10,000 switches per second.
4.3 Interrupt Latency
Interrupt latency measures the time from hardware interrupt assertion to execution of the first instruction in the interrupt service routine (ISR). This metric is critical for applications with hard real-time requirements.
Measurement Configuration
Interrupt latency measurements captured:
- Best case: System idle, no pending operations
- Typical case: One task running, no critical sections
- Worst case: Kernel critical section active
| Platform | Scenario | FreeRTOS | Zephyr |
|---|---|---|---|
| STM32F407 @ 168MHz | Best Case | 0.18 us | 0.22 us |
| STM32F407 @ 168MHz | Typical | 0.24 us | 0.31 us |
| STM32F407 @ 168MHz | Worst Case | 1.8 us | 2.4 us |
| nRF52840 @ 64MHz | Best Case | 0.42 us | 0.56 us |
| nRF52840 @ 64MHz | Typical | 0.58 us | 0.78 us |
| nRF52840 @ 64MHz | Worst Case | 4.2 us | 5.8 us |
Real-Time Considerations
Worst-case interrupt latency often determines system suitability for hard real-time applications. Both FreeRTOS and Zephyr support interrupt nesting and provide mechanisms to minimize critical section duration. For applications requiring sub-microsecond interrupt response, consider hardware interrupt controllers that bypass RTOS involvement entirely.
4.4 Benchmark Methodology
Use the following reference method to reproduce the figures above on your own target; results vary with silicon, clock configuration, compiler and kernel options:
Hardware Configuration
- Development boards from original manufacturers (STM32 Nucleo, Nordic DK, ESP32-DevKitC)
- External crystal oscillators for timing accuracy
- Measurements captured via logic analyzer (Saleae Logic Pro 16) or oscilloscope (Keysight DSOX3024T)
- Power supply: Regulated bench supply at nominal voltage
Software Configuration
- FreeRTOS: Version 11.0.1 (December 2023) or later
- Zephyr: Version 3.7.0 LTS or later
- Compiler: ARM GCC 13.2, optimization level -Os
- Configurations: Default release configurations with debugging disabled
Statistical Analysis
- Minimum 1000 iterations per measurement
- Results report mean values with standard deviation
- Outliers (>3 standard deviations) excluded from analysis
- Warm-up period of 100 iterations before measurement
Performance Benchmark Summary (Normalized to FreeRTOS = 1.0)
FreeRTOS Zephyr
-------- ------
Memory (Minimal) 1.00 1.71
Memory (IoT App) 1.00 1.86
Memory (BLE Full) 1.00 1.14
Context Switch 1.00 1.33
Interrupt Latency 1.00 1.30
API Call Overhead 1.00 1.18
Key: Lower is better for all metrics
Note: Zephyr's additional overhead reflects richer
feature set including devicetree integration,
comprehensive logging, and hardware abstraction.
Figure 4.1: Normalized performance comparison
Chapter 5: Cloud Integration Patterns
Modern embedded systems increasingly require cloud connectivity for data aggregation, remote management, and over-the-air updates. This chapter examines cloud integration approaches for both FreeRTOS and Zephyr, focusing on the three most relevant platforms: AWS IoT Core, Microsoft Azure IoT, and the emerging Matter protocol for smart home applications.
5.1 AWS IoT Core Integration
AWS IoT Core provides a managed cloud platform for connecting embedded devices to Amazon Web Services. The platform supports MQTT, HTTPS, and WebSocket protocols, with features including device shadows, rules engine, and fleet management.
FreeRTOS AWS Integration
FreeRTOS enjoys first-party AWS support through the AWS IoT Device SDK for Embedded C. This SDK provides production-ready implementations optimized for resource-constrained devices:
/* AWS IoT Device Shadow Update Example (FreeRTOS) */
#include "shadow.h"
#include "core_json.h"
static char shadowUpdateDocument[256];
ShadowStatus_t updateDeviceShadow(float temperature, bool heaterOn)
{
ShadowStatus_t status;
size_t documentLength;
/* Build shadow document */
documentLength = snprintf(
shadowUpdateDocument,
sizeof(shadowUpdateDocument),
"{"
"\"state\":{"
"\"reported\":{"
"\"temperature\":%.2f,"
"\"heaterOn\":%s,"
"\"firmwareVersion\":\"%s\""
"}"
"}"
"}",
temperature,
heaterOn ? "true" : "false",
FIRMWARE_VERSION
);
/* Publish shadow update */
status = Shadow_Update(
&shadowContext,
THING_NAME,
strlen(THING_NAME),
shadowUpdateDocument,
documentLength
);
return status;
}
/* Delta callback - invoked when desired state changes */
void shadowDeltaCallback(const char *pThingName,
const char *pDeltaDocument,
size_t deltaDocumentLength)
{
JSONStatus_t result;
char *outValue;
size_t outValueLength;
/* Parse desired heater state */
result = JSON_Search(
pDeltaDocument,
deltaDocumentLength,
"state.heaterOn",
strlen("state.heaterOn"),
&outValue,
&outValueLength
);
if (result == JSONSuccess) {
bool desiredState = (strncmp(outValue, "true", 4) == 0);
setHeaterState(desiredState);
}
}
Zephyr AWS Integration
Zephyr integrates with AWS IoT Core through its native networking stack and third-party libraries. While not officially supported by AWS, mature community solutions exist:
/* AWS IoT Connection using Zephyr networking */
#include <zephyr/kernel.h>
#include <zephyr/net/socket.h>
#include <zephyr/net/mqtt.h>
#include <zephyr/net/tls_credentials.h>
static struct mqtt_client client;
static uint8_t rx_buffer[256];
static uint8_t tx_buffer[256];
int aws_iot_connect(void)
{
struct sockaddr_in broker;
int err;
/* Configure broker address */
broker.sin_family = AF_INET;
broker.sin_port = htons(CONFIG_AWS_IOT_PORT);
net_addr_pton(AF_INET, CONFIG_AWS_IOT_BROKER_HOSTNAME,
&broker.sin_addr);
/* Initialize MQTT client */
mqtt_client_init(&client);
client.broker = &broker;
client.evt_cb = mqtt_evt_handler;
client.client_id.utf8 = CONFIG_AWS_IOT_CLIENT_ID;
client.client_id.size = strlen(CONFIG_AWS_IOT_CLIENT_ID);
client.protocol_version = MQTT_VERSION_3_1_1;
/* TLS configuration */
client.transport.type = MQTT_TRANSPORT_SECURE;
struct mqtt_sec_config *tls = &client.transport.tls.config;
tls->peer_verify = TLS_PEER_VERIFY_REQUIRED;
tls->cipher_list = NULL;
tls->sec_tag_list = sec_tag_list;
tls->sec_tag_count = ARRAY_SIZE(sec_tag_list);
tls->hostname = CONFIG_AWS_IOT_BROKER_HOSTNAME;
/* Buffers */
client.rx_buf = rx_buffer;
client.rx_buf_size = sizeof(rx_buffer);
client.tx_buf = tx_buffer;
client.tx_buf_size = sizeof(tx_buffer);
/* Connect */
err = mqtt_connect(&client);
if (err) {
LOG_ERR("MQTT connect failed: %d", err);
return err;
}
return 0;
}
5.2 Azure IoT Ecosystem
Microsoft Azure IoT Hub provides device connectivity, management, and integration with Azure cloud services. Following Microsoft’s acquisition of ThreadX and contribution to Eclipse Foundation, the Azure RTOS ecosystem has evolved significantly.
Azure RTOS (Eclipse ThreadX) Context
While not the focus of this document, Azure RTOS (now Eclipse ThreadX) warrants mention as Microsoft’s traditional embedded platform. ThreadX provides Azure IoT middleware including:
- Azure IoT Hub device client
- Azure IoT Plug and Play support
- Device Update for IoT Hub
- Azure Defender for IoT integration
FreeRTOS Azure Integration
Microsoft provides the Azure IoT Middleware for FreeRTOS, enabling FreeRTOS-based devices to connect to Azure IoT Hub:
/* Azure IoT Hub connection with FreeRTOS */
#include "azure_iot_hub_client.h"
#include "azure_iot_provisioning_client.h"
static AzureIoTHubClient_t hubClient;
AzureIoTResult_t initializeAzureIoT(void)
{
AzureIoTResult_t result;
AzureIoTHubClientOptions_t options = { 0 };
/* Initialize with connection string or DPS */
result = AzureIoTHubClient_Init(
&hubClient,
pHostname, hostnameLength,
pDeviceId, deviceIdLength,
&options
);
if (result != eAzureIoTSuccess) {
return result;
}
/* Set symmetric key authentication */
result = AzureIoTHubClient_SetSymmetricKey(
&hubClient,
pSymmetricKey,
symmetricKeyLength,
NULL /* HMAC function */
);
return result;
}
/* Send telemetry to Azure IoT Hub */
AzureIoTResult_t sendTelemetry(float temperature, float humidity)
{
char telemetryPayload[128];
size_t payloadLength;
payloadLength = snprintf(
telemetryPayload, sizeof(telemetryPayload),
"{\"temperature\":%.2f,\"humidity\":%.2f}",
temperature, humidity
);
return AzureIoTHubClient_SendTelemetry(
&hubClient,
telemetryPayload,
payloadLength,
NULL, /* Properties */
eAzureIoTHubMessageQoS1
);
}
Zephyr Azure Integration
Zephyr provides native Azure IoT support through the Azure SDK for Embedded C, which has been ported to the Zephyr networking stack:
/* prj.conf for Azure IoT Hub */
CONFIG_AZURE_IOT_HUB=y
CONFIG_AZURE_IOT_HUB_DPS=y
CONFIG_AZURE_IOT_HUB_HOSTNAME="your-hub.azure-devices.net"
CONFIG_AZURE_IOT_HUB_DEVICE_ID="your-device-id"
5.3 Matter Protocol Support
Matter (formerly Project CHIP) represents the smart home industry’s effort to create a unified, IP-based protocol for device interoperability. Developed by the Connectivity Standards Alliance (CSA) with backing from Apple, Google, Amazon, and Samsung, Matter has significant implications for RTOS selection in consumer IoT.
Zephyr as Reference Platform
The official Matter SDK uses Zephyr as one of its primary reference platforms, alongside Linux and other RTOSes. This first-party support provides several advantages:
- Reference implementations tested on Zephyr
- Nordic nRF Connect SDK (Zephyr-based) is a primary development target
- Continuous integration testing on Zephyr platforms
- Direct contribution path for Zephyr-specific features
/* Matter device initialization on Zephyr */
#include <app/server/Server.h>
#include <app/clusters/on-off-server/on-off-server.h>
using namespace chip;
using namespace chip::app;
class AppTask {
public:
CHIP_ERROR Init() {
/* Initialize Matter stack */
ReturnErrorOnFailure(Server::GetInstance().Init());
/* Initialize application-specific clusters */
InitOnOffCluster();
return CHIP_NO_ERROR;
}
void InitOnOffCluster() {
/* Register attribute change callback */
Clusters::OnOff::Attributes::OnOff::Set(
kLightEndpointId,
mLightState
);
}
void UpdateLightState(bool newState) {
mLightState = newState;
/* Update Matter attribute */
Clusters::OnOff::Attributes::OnOff::Set(
kLightEndpointId,
mLightState
);
/* Control physical hardware */
SetLightOutput(mLightState);
}
private:
bool mLightState = false;
static constexpr EndpointId kLightEndpointId = 1;
};
FreeRTOS Matter Support
FreeRTOS Matter support is available through ESP-IDF (which uses FreeRTOS as its RTOS layer) and community ports. Espressif has made significant investments in Matter support for ESP32:
/* Matter on ESP32 with ESP-IDF/FreeRTOS */
#include "esp_matter.h"
#include "esp_matter_attribute_utils.h"
using namespace esp_matter;
static void app_event_cb(
const ChipDeviceEvent *event,
intptr_t arg)
{
switch (event->Type) {
case chip::DeviceLayer::DeviceEventType::kCommissioningComplete:
ESP_LOGI(TAG, "Commissioning complete");
break;
default:
break;
}
}
void app_main(void)
{
/* Initialize NVS */
nvs_flash_init();
/* Create Matter node */
node::config_t node_config;
node_t *node = node::create(&node_config, app_event_cb, NULL);
/* Add on/off light endpoint */
on_off_light::config_t light_config;
endpoint_t *endpoint = on_off_light::create(
node, &light_config, ENDPOINT_FLAG_NONE, NULL);
/* Start Matter */
esp_matter::start(app_attribute_update_cb);
}
Matter Selection Guidance
For new smart home product development targeting Matter certification, Zephyr provides the most direct path due to its status as a reference platform. For ESP32-based products, ESP-IDF (FreeRTOS) offers excellent Matter support through Espressif’s substantial investment in the protocol.
Chapter 6: Safety Certification Pathways
Safety certification represents a critical consideration for embedded systems deployed in applications where failures could result in injury, death, or significant property damage. This chapter examines certification pathways for FreeRTOS and Zephyr across three major safety standards: IEC 61508 (industrial), ISO 26262 (automotive), and DO-178C (avionics).
6.1 IEC 61508 Compliance
IEC 61508 “Functional Safety of Electrical/Electronic/Programmable Electronic Safety-related Systems” serves as the foundational standard for industrial safety-critical systems. The standard defines Safety Integrity Levels (SIL) from SIL 1 (lowest) to SIL 4 (highest), with each level imposing increasingly stringent requirements on development processes, testing, and verification.
FreeRTOS Pathway: SAFERTOS
WITTENSTEIN High Integrity Systems offers SAFERTOS, a safety-critical derivative of FreeRTOS pre-certified to IEC 61508 SIL 3. SAFERTOS provides:
- Pre-certification Package: Complete certification evidence including safety manual, hazard analysis, and test reports
- Source Code Traceability: Bidirectional requirements traceability from requirements to code to tests
- Development Process: Developed according to IEC 61508 Part 3 requirements
- Deployment Flexibility: Certified component that can be integrated into larger certified systems
| Aspect | SAFERTOS | Standard FreeRTOS |
|---|---|---|
| IEC 61508 Pre-certified | Yes (SIL 3) | No |
| Certification Evidence | Included | Not available |
| Licensing | Commercial (per-project) | MIT (free) |
| API Compatibility | Near-identical to FreeRTOS | N/A |
| Support | Commercial support included | Community |
Zephyr Pathway
Zephyr pursues IEC 61508 certification through its Safety Working Group and Long-Term Support (LTS) releases. The approach differs from SAFERTOS:
- Safety-Certified Configuration: Specific Zephyr configurations certified rather than entire codebase
- LTS Foundation: Safety certification builds upon LTS releases (Zephyr 3.7 LTS and later)
- Community + Commercial: Certification efforts supported by both community and commercial entities
- Third-Party Certification: Companies like Parasoft and AdaCore provide Zephyr certification services
Certification Reality Check
Pre-certification reduces but does not eliminate certification effort. System-level certification still requires hazard analysis, failure modes analysis, and integration testing specific to your application. Budget 30-50% additional certification effort beyond the pre-certified RTOS component.
6.2 ISO 26262 Automotive
ISO 26262 “Road vehicles - Functional safety” adapts IEC 61508 for automotive applications. The standard defines Automotive Safety Integrity Levels (ASIL) from ASIL A (lowest) to ASIL D (highest), with ASIL D requirements comparable to SIL 3.
Automotive RTOS Requirements
ISO 26262 imposes specific requirements on software components:
- Freedom from Interference: Software partitioning preventing faults from propagating
- Memory Protection: MPU/MMU utilization to isolate safety-critical functions
- Timing Guarantees: Worst-case execution time (WCET) analysis
- Diagnostic Coverage: Self-test and monitoring capabilities
FreeRTOS Automotive Options
Several pathways exist for automotive FreeRTOS deployment:
- SAFERTOS: Pre-certified to ISO 26262 ASIL D, direct integration path
- Third-party certification of FreeRTOS-based systems: safety consultancies can support an ISO 26262 argument for a specific FreeRTOS configuration; confirm the scope of any certificate before relying on it
- Custom Certification: Organizations can pursue independent certification using standard FreeRTOS as base
Zephyr Automotive Initiatives
Zephyr’s automotive adoption is growing through several initiatives:
- AUTOSAR Adaptive Platform: Zephyr exploration as AUTOSAR Classic alternative for specific ECUs
- Safety Working Group: Formal safety analysis and documentation
- Hardware Support: Automotive-qualified MCU support (NXP S32, Infineon AURIX)
/* Zephyr Memory Protection for Safety-Critical Applications */
/* prj.conf safety configuration */
# Enable Memory Protection Unit
CONFIG_USERSPACE=y
CONFIG_MPU=y
CONFIG_MPU_STACK_GUARD=y
CONFIG_MPU_ALLOW_FLASH_WRITE=n
# Enable stack overflow detection
CONFIG_STACK_SENTINEL=y
CONFIG_STACK_POINTER_RANDOM=y
# Hardware stack protection
CONFIG_HW_STACK_PROTECTION=y
# Memory domain configuration
CONFIG_MAX_DOMAIN_PARTITIONS=8
6.3 DO-178C Avionics
DO-178C “Software Considerations in Airborne Systems and Equipment Certification” governs software in airborne systems. The standard defines Design Assurance Levels (DAL) from DAL E (lowest) to DAL A (highest), with DAL A requiring the most rigorous development and verification processes.
Avionics RTOS Landscape
The avionics market has traditionally been dominated by commercial RTOSes:
- VxWorks 653: ARINC 653 compliant, extensive DO-178C heritage
- INTEGRITY-178: NSA EAL 6+ certified, DO-178C DAL A heritage
- LynxOS-178: DO-178C certified, POSIX-compliant
Open Source in Avionics
Open-source RTOS adoption in avionics remains limited but growing:
FreeRTOS/SAFERTOS: SAFERTOS has achieved DO-178C DAL C certification for specific configurations. Higher DAL levels require additional certification effort and custom development.
Zephyr: No current DO-178C certifications. The Zephyr Safety Working Group has expressed interest in avionics applications, but certification timeline remains uncertain.
| Standard | FreeRTOS Path | Zephyr Path | Recommendation |
|---|---|---|---|
| IEC 61508 SIL 3 | SAFERTOS (mature) | LTS + third-party (emerging) | SAFERTOS for fastest path |
| ISO 26262 ASIL D | SAFERTOS (mature) | Custom certification (limited) | SAFERTOS or commercial RTOS |
| DO-178C DAL A | SAFERTOS (DAL C available) | Not available | Commercial RTOS recommended |
Critical Safety Guidance
For applications requiring DAL A (catastrophic failure consequences) or ASIL D certification, we strongly recommend engaging with certification specialists early in the design phase. The RTOS selection is one component of a comprehensive safety architecture that must be designed holistically.
Chapter 7: Development Experience
Developer productivity significantly impacts project timelines and total cost of ownership. This chapter compares the development experience across toolchains, CI/CD integration, debugging capabilities, and modern development workflows for both FreeRTOS and Zephyr.
7.1 Toolchain Comparison
FreeRTOS Toolchain Options
FreeRTOS offers flexibility in toolchain selection, typically inheriting the build system from the vendor SDK or project requirements:
- Vendor IDEs: STM32CubeIDE, ESP-IDF/VS Code, MPLAB X, MCUXpresso
- Generic Build Systems: Make, CMake (increasingly common)
- Compilers: GCC (ARM, Xtensa), IAR, Keil MDK, LLVM/Clang
The FreeRTOS project itself does not mandate any specific build system. This flexibility can be advantageous for integration into existing projects but may require more initial setup effort for new projects.
# FreeRTOS CMake Integration Example
cmake_minimum_required(VERSION 3.16)
project(freertos_app C ASM)
# Set FreeRTOS source directory
set(FREERTOS_DIR ${CMAKE_SOURCE_DIR}/lib/FreeRTOS-Kernel)
# Add FreeRTOS sources
add_library(freertos STATIC
${FREERTOS_DIR}/tasks.c
${FREERTOS_DIR}/queue.c
${FREERTOS_DIR}/list.c
${FREERTOS_DIR}/timers.c
${FREERTOS_DIR}/portable/GCC/ARM_CM4F/port.c
${FREERTOS_DIR}/portable/MemMang/heap_4.c
)
target_include_directories(freertos PUBLIC
${FREERTOS_DIR}/include
${FREERTOS_DIR}/portable/GCC/ARM_CM4F
${CMAKE_SOURCE_DIR}/config # FreeRTOSConfig.h location
)
# Application
add_executable(${PROJECT_NAME}
src/main.c
src/startup.c
)
target_link_libraries(${PROJECT_NAME} freertos)
Zephyr Toolchain
Zephyr employs a standardized, modern build system based on CMake, Ninja, and the west meta-tool:
- Build System: CMake with Zephyr-specific extensions
- Build Tool: Ninja (default) or Make
- Meta Tool: West for workspace management, building, flashing, debugging
- Compilers: Zephyr SDK (ARM GCC), custom toolchains supported
# Zephyr project structure
my_project/
├── CMakeLists.txt
├── prj.conf
├── src/
│ └── main.c
├── boards/
│ └── custom_board.overlay # Optional devicetree overlay
└── west.yml # Manifest for workspace
# CMakeLists.txt (minimal)
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(my_project)
target_sources(app PRIVATE src/main.c)
# Build commands
west build -b nrf52840dk_nrf52840 my_project
west flash
west debug
IDE Support Comparison
| IDE/Editor | FreeRTOS Support | Zephyr Support |
|---|---|---|
| VS Code | Excellent (multiple extensions) | Excellent (nRF Connect, Zephyr IDE) |
| Eclipse | Good (vendor plugins) | Good (Eclipse CDT) |
| CLion | Good (CMake projects) | Excellent (native CMake) |
| Vendor IDEs | Excellent (first-party) | Limited (Nordic only) |
| Command Line | Good (varies by setup) | Excellent (west) |
7.2 CI/CD Integration
Continuous integration and deployment have become essential for professional embedded development. Both RTOSes can be integrated into modern CI/CD pipelines, with different approaches.
FreeRTOS CI/CD
FreeRTOS CI/CD integration typically leverages vendor toolchains or generic ARM GCC:
# GitHub Actions for FreeRTOS (ESP32 example)
name: FreeRTOS ESP32 Build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
container: espressif/idf:v5.1
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Build Project
run: |
. /opt/esp/idf/export.sh
idf.py build
- name: Run Unit Tests
run: |
. /opt/esp/idf/export.sh
idf.py -T test_component flash monitor
- name: Upload Artifacts
uses: actions/upload-artifact@v4
with:
name: firmware
path: build/*.bin
Zephyr CI/CD
Zephyr provides first-class CI/CD support with twister (the test runner) and standardized build procedures:
# GitHub Actions for Zephyr
name: Zephyr Build and Test
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
container: zephyrproject/ci:latest
steps:
- uses: actions/checkout@v4
- name: Initialize West Workspace
run: |
west init -l .
west update
- name: Build for Multiple Boards
run: |
west build -b nrf52840dk_nrf52840 app
west build -b nucleo_f401re app
west build -b esp32_devkitc_wroom app
- name: Run Twister Tests
run: |
./scripts/twister -T tests/ -p native_sim \
--inline-logs --integration
- name: Static Analysis
run: |
west build -b native_sim app -- -DCONFIG_ASSERT=y
./scripts/checkpatch.pl --git HEAD~1
- name: Upload Test Results
uses: actions/upload-artifact@v4
with:
name: test-results
path: twister-out/
CI/CD Advantage
Zephyr’s standardized build system and twister test framework significantly simplify CI/CD integration. The ability to run tests on native_posix (simulated environment) enables comprehensive testing without hardware. FreeRTOS achieves similar results but requires more custom scripting.
7.3 Debugging Capabilities
Debug Probe Support
Both RTOSes support standard debug probes, with debugging experience largely determined by the probe and IDE combination:
| Debug Probe | FreeRTOS | Zephyr |
|---|---|---|
| J-Link | Excellent (RTOS awareness) | Excellent (RTOS awareness) |
| ST-Link | Good | Good |
| CMSIS-DAP | Good | Good |
| OpenOCD | Good | Excellent (native support) |
| pyOCD | Good | Excellent (west integration) |
RTOS-Aware Debugging
RTOS-aware debugging provides visibility into task states, stack usage, and synchronization primitives:
FreeRTOS:
- SEGGER SystemView integration for real-time tracing
- FreeRTOS+Trace (Percepio Tracealyzer) support
- J-Link RTOS plugin for thread-aware debugging
- configUSE_TRACE_FACILITY for kernel-level hooks
Zephyr:
- Built-in thread analyzer subsystem
- SEGGER SystemView integration
- Percepio Tracealyzer support
- Native shell commands for runtime inspection
- Comprehensive logging subsystem
/* Zephyr Runtime Debug Commands (Shell) */
uart:~$ kernel threads
Thread 0x20002000 (main)
State: running
Priority: 0
Stack size: 2048
Stack used: 892
Thread 0x20002200 (sensor_thread)
State: sleeping
Priority: 5
Stack size: 1024
Stack used: 456
uart:~$ kernel stacks
0x20002000 main (real size 2048): unused 1156 usage 892 / 2048 (43 %)
0x20002200 sensor (real size 1024): unused 568 usage 456 / 1024 (44 %)
0x20002400 idle (real size 320): unused 280 usage 40 / 320 (12 %)
Logging and Diagnostics
Zephyr provides a more comprehensive built-in logging system:
/* Zephyr Logging Example */
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(my_module, LOG_LEVEL_DBG);
void some_function(void)
{
LOG_INF("Information message");
LOG_WRN("Warning: value %d exceeds threshold", value);
LOG_ERR("Error occurred: %d", err);
LOG_DBG("Debug: entering state %s", state_name);
/* Hexdump for binary data */
LOG_HEXDUMP_INF(buffer, sizeof(buffer), "Received data");
}
Chapter 8: Migration Strategies
Organizations may need to migrate between RTOSes due to evolving requirements, ecosystem preferences, or strategic decisions. This chapter provides practical guidance for migration scenarios, with emphasis on risk mitigation and incremental approaches.
8.1 FreeRTOS to Zephyr Migration
Migrating from FreeRTOS to Zephyr is the more common direction, driven by needs for advanced networking, better hardware abstraction, or modern build systems.
API Mapping
The following table maps common FreeRTOS APIs to Zephyr equivalents:
| FreeRTOS API | Zephyr Equivalent | Notes |
|---|---|---|
xTaskCreate() | k_thread_create() | Different parameter order |
vTaskDelay() | k_sleep() | Use K_MSEC() macro |
vTaskDelayUntil() | k_sleep(K_TIMEOUT_ABS_MS()) | Absolute timeout |
xSemaphoreCreateBinary() | K_SEM_DEFINE() | Static allocation preferred |
xSemaphoreTake() | k_sem_take() | Similar semantics |
xSemaphoreGive() | k_sem_give() | Similar semantics |
xQueueCreate() | K_MSGQ_DEFINE() | Message queue |
xQueueSend() | k_msgq_put() | Copy semantics |
xQueueReceive() | k_msgq_get() | Copy semantics |
xTimerCreate() | K_TIMER_DEFINE() | Static allocation |
taskENTER_CRITICAL() | irq_lock() / k_spin_lock() | k_sched_lock() only blocks preemption, not interrupts |
Migration Code Example
/* FreeRTOS Original Code */
SemaphoreHandle_t dataSem;
QueueHandle_t dataQueue;
void producer_task(void *pvParams)
{
SensorData_t data;
for(;;) {
data = readSensor();
xQueueSend(dataQueue, &data, portMAX_DELAY);
xSemaphoreGive(dataSem);
vTaskDelay(pdMS_TO_TICKS(100));
}
}
void init_tasks(void)
{
dataSem = xSemaphoreCreateBinary();
dataQueue = xQueueCreate(10, sizeof(SensorData_t));
xTaskCreate(producer_task, "producer", 256, NULL, 2, NULL);
}
/* Zephyr Migrated Code */
K_SEM_DEFINE(data_sem, 0, 1);
K_MSGQ_DEFINE(data_queue, sizeof(SensorData_t), 10, 4);
K_THREAD_STACK_DEFINE(producer_stack, 1024);
struct k_thread producer_thread;
void producer_task(void *p1, void *p2, void *p3)
{
SensorData_t data;
while (1) {
data = read_sensor();
k_msgq_put(&data_queue, &data, K_FOREVER);
k_sem_give(&data_sem);
k_sleep(K_MSEC(100));
}
}
void init_tasks(void)
{
k_thread_create(&producer_thread, producer_stack,
K_THREAD_STACK_SIZEOF(producer_stack),
producer_task, NULL, NULL, NULL,
2, 0, K_NO_WAIT);
}
8.2 Abstraction Layer Approaches
For projects requiring portability between RTOSes or gradual migration, abstraction layers provide a viable approach.
CMSIS-RTOS2 Abstraction
The ARM CMSIS-RTOS2 API provides a standardized interface supported by multiple RTOSes:
/* CMSIS-RTOS2 Portable Code */
#include "cmsis_os2.h"
osThreadId_t sensorThreadId;
osSemaphoreId_t dataSemId;
osMessageQueueId_t dataQueueId;
void sensor_thread(void *argument)
{
SensorData_t data;
for(;;) {
data = readSensor();
osMessageQueuePut(dataQueueId, &data, 0, osWaitForever);
osSemaphoreRelease(dataSemId);
osDelay(100);
}
}
void app_init(void)
{
dataSemId = osSemaphoreNew(1, 0, NULL);
dataQueueId = osMessageQueueNew(10, sizeof(SensorData_t), NULL);
const osThreadAttr_t threadAttr = {
.name = "SensorThread",
.stack_size = 1024,
.priority = osPriorityNormal
};
sensorThreadId = osThreadNew(sensor_thread, NULL, &threadAttr);
}
Custom Abstraction Layer
For finer control, a custom abstraction layer can be implemented:
/* rtos_abstraction.h */
#ifndef RTOS_ABSTRACTION_H
#define RTOS_ABSTRACTION_H
#if defined(USE_FREERTOS)
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
typedef SemaphoreHandle_t rtos_sem_t;
#define rtos_sem_take(sem, timeout) \
xSemaphoreTake(sem, pdMS_TO_TICKS(timeout))
#define rtos_sem_give(sem) xSemaphoreGive(sem)
#define rtos_delay_ms(ms) vTaskDelay(pdMS_TO_TICKS(ms))
#elif defined(USE_ZEPHYR)
#include <zephyr/kernel.h>
typedef struct k_sem rtos_sem_t;
#define rtos_sem_take(sem, timeout) \
k_sem_take(&sem, K_MSEC(timeout))
#define rtos_sem_give(sem) k_sem_give(&sem)
#define rtos_delay_ms(ms) k_sleep(K_MSEC(ms))
#endif
#endif /* RTOS_ABSTRACTION_H */
8.3 Risk Mitigation
RTOS migration carries inherent risks that must be carefully managed:
Common Migration Risks
- Timing Behavior Changes: Different scheduler implementations may alter timing characteristics
- Stack Size Differences: Context save/restore overhead varies between RTOSes
- Priority Mapping: Priority schemes may differ (FreeRTOS: higher number = higher priority; some RTOSes: reversed)
- API Semantic Differences: Subtle behavioral differences in seemingly equivalent APIs
- Driver Compatibility: Peripheral drivers must be reimplemented or adapted
Mitigation Strategies
- Incremental Migration: Migrate subsystems one at a time, validating each step
- Comprehensive Testing: Develop extensive test suites before migration
- Timing Validation: Use logic analyzers to verify timing requirements post-migration
- Stack Analysis: Perform stack high-water-mark analysis on both platforms
- Parallel Operation: Run both systems in parallel during transition when possible
Migration Timeline
Budget 2-4x the estimated migration effort for unanticipated issues. Complex projects with custom drivers, networking stacks, or safety requirements often require significantly more effort than initially estimated. Consider engaging RTOS migration specialists for critical projects.
Chapter 9: Decision Framework
This chapter synthesizes the preceding analysis into a practical decision framework for RTOS selection. We present a weighted criteria matrix and specific use case recommendations.
9.1 Selection Criteria Matrix
The following matrix scores FreeRTOS and Zephyr across key selection criteria. Scores range from 1 (poor) to 5 (excellent), with weights reflecting typical project priorities:
| Criterion | Weight | FreeRTOS | Zephyr | Notes |
|---|---|---|---|---|
| Minimal Memory Footprint | High | 5 | 3 | FreeRTOS significantly smaller |
| Learning Curve | Medium | 5 | 3 | FreeRTOS simpler to learn |
| Hardware Abstraction | High | 2 | 5 | Zephyr comprehensive HAL |
| Board/Platform Support | Medium | 4 | 5 | Both extensive, Zephyr unified |
| Bluetooth Stack Quality | High* | 3 | 5 | Zephyr certified stack |
| Thread/Matter Support | High* | 3 | 5 | Zephyr is reference platform |
| AWS IoT Integration | High* | 5 | 3 | FreeRTOS first-party support |
| Safety Certification | Critical* | 4 | 3 | SAFERTOS mature path |
| Build System Modernity | Medium | 3 | 5 | Zephyr CMake/west |
| CI/CD Integration | Medium | 3 | 5 | Zephyr twister framework |
| Documentation Quality | Medium | 4 | 4 | Both good, different styles |
| Community Size | Low | 5 | 4 | FreeRTOS larger historical base |
| Long-term Viability | High | 5 | 5 | Both strongly backed |
* Weight varies significantly by project type
9.2 Use Case Recommendations
Choose FreeRTOS When:
Resource-Constrained Devices
- Less than 32KB Flash available
- Less than 8KB RAM available
- Cost-sensitive high-volume products
- Simple sensor nodes without networking
AWS-Centric IoT
- AWS IoT Core as primary cloud
- Need for AWS IoT Device Defender
- Leveraging AWS IoT Greengrass
- Using AWS IoT ExpressLink modules
Team Considerations
- Team experienced with FreeRTOS
- Transitioning from bare-metal
- Limited ramp-up time available
- Preference for simpler architecture
Specific Platforms
- ESP32 with ESP-IDF
- STM32 with CubeMX workflow
- Projects using vendor SDKs
- Legacy system integration
Choose Zephyr When:
Advanced Connectivity
- Bluetooth 5.x with advanced features
- Thread networking required
- Matter protocol certification
- Multi-protocol devices
Hardware Flexibility
- Multi-vendor hardware strategy
- Anticipated platform changes
- Need unified driver APIs
- Custom board development
Development Practices
- Modern CI/CD requirements
- Comprehensive testing needs
- DevOps-oriented teams
- Linux development familiarity
Specific Ecosystems
- Nordic nRF52/53/91 series
- Intel embedded platforms
- Products requiring LTS
- Open-source preference
Decision Flowchart
START
│
▼
┌───────────────────────┐
│ Memory < 32KB Flash │
│ or < 8KB RAM? │
└───────────┬───────────┘
YES │ NO
┌───────────┘ └───────────┐
▼ ▼
┌─────────┐ ┌───────────────────────┐
│FreeRTOS │ │ BLE 5.x / Thread / │
│RECOMMENDED│ │ Matter required? │
└─────────┘ └───────────┬───────────┘
YES │ NO
┌───────────┘ └───────────┐
▼ ▼
┌─────────┐ ┌───────────────────────┐
│ Zephyr │ │ AWS IoT Core │
│RECOMMENDED│ │ primary cloud? │
└─────────┘ └───────────┬───────────┘
YES │ NO
┌───────────┘ └───────────┐
▼ ▼
┌─────────┐ ┌───────────────────────┐
│FreeRTOS │ │ Multi-vendor HW or │
│RECOMMENDED│ │ platform flexibility? │
└─────────┘ └───────────┬───────────┘
YES │ NO
┌───────────┘ └───────────┐
▼ ▼
┌─────────┐ ┌─────────────┐
│ Zephyr │ │ Either viable│
│RECOMMENDED│ │ Evaluate team│
└─────────┘ │ experience │
└─────────────┘
Figure 9.1: RTOS selection decision flowchart
Conclusion: Conclusion and Recommendations
The choice between FreeRTOS and Zephyr represents a consequential architectural decision with long-term implications for product development, maintenance, and evolution. After comprehensive analysis across technical capabilities, ecosystem factors, and practical considerations, we offer the following conclusions:
FreeRTOS Remains the Right Choice for Many Applications
FreeRTOS’s enduring popularity reflects genuine strengths: minimal footprint, simplicity, extensive deployment history, and first-party AWS integration. For resource-constrained devices, AWS-centric IoT deployments, and teams prioritizing rapid time-to-market with familiar tools, FreeRTOS continues to be an excellent choice. The availability of SAFERTOS provides a mature pathway to safety certification when required.
Zephyr Represents the Future of Open-Source Embedded
Zephyr’s trajectory suggests it will become the dominant open-source RTOS for complex connected devices. Its comprehensive hardware abstraction, certified wireless stacks, modern build system, and strong corporate backing position it well for the increasingly connected, multi-protocol future of embedded systems. Organizations building products with 5+ year lifecycles should seriously consider Zephyr’s advantages in maintainability and portability.
The Decision is Rarely Binary
Many organizations successfully deploy both RTOSes across different product lines, selecting the optimal platform for each application’s specific requirements. This portfolio approach leverages FreeRTOS’s efficiency for simple devices while employing Zephyr’s capabilities for complex connected products.
Investment in Either Platform is Sound
Both FreeRTOS (AWS backing) and Zephyr (Linux Foundation + major semiconductor vendors) have strong long-term viability. Technical debt concerns that might arise from RTOS selection are manageable through abstraction layers and careful architecture. The greater risk lies in selecting an RTOS poorly suited to the application’s requirements rather than in the choice between these two well-supported platforms.
Final Recommendation
Evaluate both platforms against your specific requirements using the framework provided in Chapter 9. Prototype critical functionality on both platforms if resources permit. Engage with the respective communities and ecosystems. The “best” RTOS is the one that enables your team to deliver reliable, maintainable products efficiently within your specific constraints and requirements.
Appendix A: References and Further Reading
Official Documentation
- FreeRTOS Official Documentation:
https://www.freertos.org/Documentation/ - Zephyr Project Documentation:
https://docs.zephyrproject.org/ - AWS IoT FreeRTOS Developer Guide:
https://docs.aws.amazon.com/freertos/ - Nordic nRF Connect SDK:
https://developer.nordicsemi.com/
Technical References
- Barry, R. “Mastering the FreeRTOS Real Time Kernel.” Real Time Engineers Ltd., 2016.
- Zephyr Project. “Zephyr OS Kernel Documentation.” Linux Foundation, 2024.
- ARM Ltd. “CMSIS-RTOS2 API Specification.” ARM Developer, 2023.
- Buttazzo, G. C. “Hard Real-Time Computing Systems.” Springer, 2011.
Industry Reports
- Aspencore. “2024 Embedded Markets Study.” AspenCore Media, 2024.
- Grand View Research. “Real-Time Operating System Market Analysis.” 2024.
- Microsoft/Hypothesis Group. “IoT Signals Report.” Microsoft, 2024.
- Eclipse Foundation. “IoT Developer Survey Results.” 2024.
Safety Standards
- IEC 61508:2010 “Functional safety of electrical/electronic/programmable electronic safety-related systems”
- ISO 26262:2018 “Road vehicles - Functional safety”
- DO-178C “Software Considerations in Airborne Systems and Equipment Certification”
Online Resources
- FreeRTOS Community Forums:
https://forums.freertos.org/ - Zephyr Discord Server:
https://discord.gg/zephyrproject - Zephyr Mailing Lists:
https://lists.zephyrproject.org/ - Embedded.fm Podcast:
https://embedded.fm/
Related services
Related white papers
Related topics
- RTOS
- Zephyr
- FreeRTOS
- embedded systems
- real-time operating system
- IoT firmware
- AWS IoT
- Azure RTOS
- safety certification
- IEC 61508
- ISO 26262
- DO-178C
- devicetree
- Kconfig
- ESP32
- STM32
- Nordic
- nRF Connect SDK
- SAFERTOS
- embedded Linux
- microcontroller OS
- context switch
- task scheduling