Skip to content
systemcoding.dev
RTOS

The Complete Guide to Getting Started With Zephyr RTOS

Learn Zephyr RTOS from install to first threads: west, Kconfig, devicetree, the build, kernel services, logging, debugging and tests, with FreeRTOS comparisons.

26 min read
Summarize in AI
Flat illustration of RTOS tasks taking turns on a timeline, with the C, Arm and Rust logos.

Zephyr looks, at first, like FreeRTOS with a lot more furniture. There is a kernel with threads and semaphores, which is familiar. Around it there is a build system based on CMake, a configuration language called Kconfig inherited from the Linux kernel, a hardware description language called devicetree inherited from the same place, a command-line tool called west, and a catalogue of several hundred supported boards. A newcomer needs a map more than a tutorial, because the pieces depend on each other and the documentation explains each one in isolation. This guide is that map. It goes from installing the tools to writing a multithreaded application with a timer, a message queue and logging, and says what each of the unfamiliar concepts is for and when to use it. It is written for Zephyr 4.1 with the Zephyr SDK 0.17, on an STM32 Nucleo-F401RE as the example board, and it points at the official documentation for details that change between releases. The reader is assumed to know C and to have some embedded experience; experience with FreeRTOS helps, and the differences are noted where they cause mistakes.

What Zephyr is

Zephyr is an open-source real-time operating system hosted by the Linux Foundation. It targets microcontrollers and small processors, and it supports Arm Cortex-M and Cortex-A, RISC-V, Xtensa, x86, ARC and others, with hundreds of boards. It is more than a scheduler. The project includes device drivers for many peripherals, networking stacks (IP, Bluetooth, CAN, USB), file systems, a shell, a logging framework, a test framework, power management and a bootloader project, MCUboot, which Zephyr develops with others.

The difference in scope from FreeRTOS is the first thing to understand. FreeRTOS is a kernel: tasks, queues, timers, and a port per architecture, with drivers and middleware coming from the chip vendor or other projects. Zephyr is a kernel plus a large body of drivers and subsystems under one build and one hardware model. Writing a Zephyr application is more like writing a Linux user program against a set of device APIs than like assembling libraries yourself, and the price is a bigger system to learn and a bigger binary: a small Zephyr image is larger than a small FreeRTOS one, though both fit in a modern microcontroller's flash.

Three decisions follow from that scope. Hardware is described, not coded: a board's pins and peripherals live in a devicetree, and drivers read it. Features are selected, not linked: you choose them in Kconfig and the build includes only what you ask for. And boards are first-class: the same application builds for many boards by changing one argument, because the board description, not the application, says where the LED is.

The pieces, and what each does

Before installing anything, here are the pieces by name, because the commands will use all of them.

PieceWhat it isWhere you meet it
westThe meta-tool: manages the workspace, wraps build, flash and debugwest build, west flash
CMake and NinjaThe build system underneath westYour application's CMakeLists.txt
KconfigA configuration language: options set to y, n or a valueprj.conf, menuconfig
DevicetreeA hardware description in a tree of nodes and propertiesBoard files, .overlay files, DT_* macros
The Zephyr SDKCross-compilers and host toolsInstalled once
BindingsYAML files describing what properties a devicetree node may haveInside dts/bindings
BoardsDescriptions of hardware: devicetree, defaults, flash runnersboards/ in the tree

The two languages, Kconfig and devicetree, do different jobs. Kconfig answers "which software features does this image include?" Devicetree answers "what hardware does this board have and how is it connected?" A UART driver needs both: a Kconfig option turns the driver on, and the devicetree says where the UART is and at what address.

Installing

The detailed procedure is in the install and blinky post, and the official Getting Started Guide is authoritative for your operating system. In outline, on Linux or macOS:

  1. Install the host tools: CMake, Ninja, Python, the device tree compiler, git.

  2. Create a Python virtual environment and install west into it.

  3. Run west init and west update to fetch the source into a workspace directory.

  4. Install the Python requirements for the tree.

  5. Run west sdk install to get the toolchain.

The workspace looks like this afterwards:

Text
zephyrproject/
  .venv/             Python virtual environment
  .west/             west's own configuration
  zephyr/            the kernel, drivers, boards, samples
  modules/           vendor HALs and libraries
  bootloader/        MCUboot
  tools/             supporting tools

The tree is large, and west update fetches many repositories; this is normal. West reads a manifest, zephyr/west.yml, that lists which repositories at which revisions make up a consistent release, so that the kernel, HAL and libraries match. Check out a release tag in zephyr/ and run west update again to get the matching set. A release tag keeps the board names and options stable; the main branch does not.

Your first build

With the tree and SDK installed, the first build is the blinky sample:

first_build.shShell
cd ~/zephyrproject/zephyr
west build -p always -b nucleo_f401re samples/basic/blinky
west flash

Four things happen in west build, and knowing them explains most later errors.

  1. CMake configures. It finds Zephyr, the SDK and the board.

  2. The devicetree is preprocessed and compiled. The board's .dts file, any overlays you provided and the bindings are combined into build/zephyr/zephyr.dts and a generated header, devicetree_generated.h, that the C code reads through DT_* macros.

  3. Kconfig is resolved. The board's defaults, the application's prj.conf and any extra fragments are merged into build/zephyr/.config, and a header autoconf.h with a CONFIG_* define per option.

  4. Ninja compiles and links. The kernel, the selected drivers and your sources become zephyr.elf, with .bin and .hex copies.

The files in build/zephyr/ are your first debugging tool. .config shows what was really enabled, which differs from what you hoped when a dependency was missing. zephyr.dts shows the final hardware description. If an option has no effect, or a device is not ready, look there first.

An application's layout

A Zephyr application is a directory with a small, fixed shape:

Text
my_app/
  CMakeLists.txt
  prj.conf
  app.overlay          optional devicetree overlay
  boards/              optional per-board config and overlays
    nucleo_f401re.conf
    nucleo_f401re.overlay
  src/
    main.c

CMakeLists.txt is three lines of substance:

CMakeLists.txtcmake
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(my_app)

target_sources(app PRIVATE src/main.c)

find_package(Zephyr ...) loads the entire Zephyr build system, which is why the file is so short. app is a library target that Zephyr creates for your code. Add more sources with more target_sources lines or a glob.

prj.conf holds Kconfig settings, one per line:

prj.confText
CONFIG_GPIO=y
CONFIG_LOG=y
CONFIG_MAIN_STACK_SIZE=2048

Anything not in the file takes its default. Per-board files, boards/<board>.conf, are merged on top for that board, and the .overlay files adjust the devicetree.

Build an application outside the Zephyr tree by pointing west at its directory:

build_app.shShell
cd ~/zephyrproject
west build -p always -b nucleo_f401re my_app

The application can live anywhere, and west finds Zephyr through the registered CMake package (the west zephyr-export step) and the environment.

Kconfig, in practice

Kconfig is a language of options with types, defaults and dependencies. Most options are booleans, CONFIG_FOO=y, and some take integers or strings. You write only the ones you want different from the defaults.

To explore, open the menu interface:

menuconfig.shShell
west build -t menuconfig

Navigate the tree, press ? on an option to read its help and its dependencies, toggle a setting, and save. West writes the change to the build directory's configuration, but the change is not persistent: the next pristine build starts from prj.conf again. To keep a setting, put it in prj.conf. This is a frequent trap for beginners who configure in the menu, rebuild with -p always and lose the change.

Dependencies are the part that confuses newcomers. An option may silently not take effect because something it depends on is off. The build prints a warning in that case:

Text
warning: CONFIG_LOG_BACKEND_UART (defined at subsys/logging/backends/Kconfig.uart:11) was assigned the value 'y' but got the value 'n'. Check these unsatisfied dependencies: ( ... )

Read these warnings. Treat them as errors in your own head, since the build continues with the wrong configuration. west build -t guiconfig offers a graphical version, and the option search at the Kconfig reference on the documentation site lists every symbol with its dependencies.

Devicetree, in practice

A devicetree is a tree of nodes, each with properties. This fragment is from a board file; the syntax is what you will read and write:

board.dtsText
/ {
    leds {
        compatible = "gpio-leds";

        green_led: led_0 {
            gpios = <&gpioa 5 GPIO_ACTIVE_HIGH>;
            label = "User LD2";
        };
    };

    aliases {
        led0 = &green_led;
    };
};

Read it as follows. A node named leds is compatible with the gpio-leds binding, which says its children are LEDs described by a gpios property. The child led_0, labelled green_led so it can be referenced, has gpios pointing at controller gpioa, pin 5, active high. An alias led0 names it so that portable code can say "the first LED" without knowing the board.

In C, you read the tree through macros that expand at compile time:

dt_use.cc
#include <zephyr/devicetree.h>
#include <zephyr/drivers/gpio.h>

#define LED_NODE DT_ALIAS(led0)

static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED_NODE, gpios);

DT_ALIAS(led0) gives the node identifier, and GPIO_DT_SPEC_GET() extracts the controller, pin and flags into a struct. There is no run-time parsing: the compiler sees constants. If the alias is missing, the build fails with a message from the macro, which is what you want.

To change the hardware description for your application, write an overlay, a file that adds or modifies nodes on top of the board's. Put app.overlay in the application directory, or boards/nucleo_f401re.overlay for one board. For example, to enable a second UART and name a pin:

app.overlayText
&usart6 {
    status = "okay";
    current-speed = <115200>;
};

/ {
    aliases {
        debug-led = &green_led;
    };
};

&usart6 refers to a node by its label and modifies it: setting status to "okay" enables the peripheral. The driver for it, if the Kconfig option is on, then initialises it at boot. A common mistake is enabling the node and forgetting the Kconfig option for the driver, or the reverse; the symptom is device_is_ready() returning false.

Bindings define the vocabulary. A compatible string names a binding file in dts/bindings, which lists the properties the node may have, their types and which are required. The build checks the devicetree against the bindings, so a typo in a property name is an error, not a silent no-op.

The kernel: threads

Now the kernel, which is the part most like FreeRTOS. A Zephyr thread has a stack, a priority, an entry function and a state. Define a thread statically with a macro:

threads.cc
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>

#define STACK_SIZE 1024
#define PRIORITY   5

static void worker(void *p1, void *p2, void *p3)
{
    ARG_UNUSED(p2);
    ARG_UNUSED(p3);

    const char *name = p1;

    for (;;) {
        printk("%s running\n", name);
        k_msleep(1000);
    }
}

K_THREAD_DEFINE(worker_a, STACK_SIZE, worker, "A", NULL, NULL, PRIORITY, 0, 0);
K_THREAD_DEFINE(worker_b, STACK_SIZE, worker, "B", NULL, NULL, PRIORITY, 0, 0);

int main(void)
{
    printk("main started\n");
    return 0;
}

K_THREAD_DEFINE allocates the stack and the thread object at compile time and starts the thread at boot, after a delay in milliseconds, the last argument; 0 starts it immediately. The arguments are the thread's name, stack size in bytes, entry function, three pointer arguments passed to the entry function, priority, options and start delay. The entry takes three void * parameters, a Zephyr convention.

Output on the console, once a second after the banner:

Text
*** Booting Zephyr OS build v4.1.0 ***
main started
A running
B running
A running
B running

main() returns after printing, and that is fine: the main thread ends, and the other threads continue. The order of "A running" and "B running" within a second depends on scheduling.

Create threads at run time with k_thread_create():

dynamic_thread.cc
K_THREAD_STACK_DEFINE(extra_stack, 1024);
static struct k_thread extra_thread;

void start_extra(void)
{
    k_thread_create(&extra_thread, extra_stack, K_THREAD_STACK_SIZEOF(extra_stack),
                    worker, "C", NULL, NULL,
                    K_PRIO_PREEMPT(5), 0, K_NO_WAIT);
}

The stack is still a static array, defined with K_THREAD_STACK_DEFINE so it has the alignment and guard the architecture needs. Zephyr's kernel objects are normally static; dynamic allocation is possible through a kernel heap but is the exception.

Priorities run the other way

This is the single most common mistake for people from FreeRTOS. In Zephyr, a lower number is a higher priority. Priority 0 outranks priority 5. Negative priorities are cooperative: a thread at a negative priority is not preempted by other threads, only by interrupts, and runs until it blocks or yields. Non-negative priorities are preemptible.

PriorityClassNotes
Negative, e.g. K_PRIO_COOP(2)CooperativeNot preempted by threads; only blocks, yields or interrupts
0 and up, e.g. K_PRIO_PREEMPT(5)PreemptiblePreempted by any thread of numerically lower priority value
Idle threadLowestRuns when nothing else is ready

The main thread's priority is CONFIG_MAIN_THREAD_PRIORITY, 0 by default, which makes it the highest preemptible priority. A thread you create at priority 5 will not preempt it, and a thread at priority -1 will preempt everything preemptible. The number of levels of each class is configurable with CONFIG_NUM_COOP_PRIORITIES and CONFIG_NUM_PREEMPT_PRIORITIES. Time slicing among equal-priority preemptible threads is optional, enabled with CONFIG_TIMESLICING and the slice length settings.

Waiting, signalling and passing data

The kernel's synchronisation objects are familiar in role, with different names.

Sleeping. k_msleep(ms) and k_sleep(K_MSEC(ms)) suspend the current thread. k_busy_wait(us) spins without yielding, for very short delays.

Semaphores. Define with K_SEM_DEFINE( name, initial_count, limit ), signal with k_sem_give(), wait with k_sem_take( &sem, timeout ). Timeouts are K_NO_WAIT, K_FOREVER or K_MSEC(n).

sem.cc
K_SEM_DEFINE(data_ready, 0, 1);

void isr_like(void)
{
    k_sem_give(&data_ready);
}

void consumer(void *a, void *b, void *c)
{
    for (;;) {
        k_sem_take(&data_ready, K_FOREVER);
        printk("data ready\n");
    }
}

Mutexes. K_MUTEX_DEFINE( name ), k_mutex_lock( &m, K_FOREVER ), k_mutex_unlock( &m ). Zephyr's mutexes support priority inheritance and are recursive.

Message queues. A fixed-size queue of fixed-size items, copied in and out:

msgq.cc
struct sample {
    uint32_t seq;
    int32_t  value;
};

K_MSGQ_DEFINE(sample_q, sizeof(struct sample), 8, 4);

void producer(void *a, void *b, void *c)
{
    uint32_t n = 0;

    for (;;) {
        uint32_t seq = n++;
        struct sample s = { .seq = seq, .value = (int32_t)((seq + 1) * 10) };

        if (k_msgq_put(&sample_q, &s, K_NO_WAIT) != 0) {
            printk("queue full, dropped %u\n", s.seq);
        }
        k_msleep(100);
    }
}

void reader(void *a, void *b, void *c)
{
    struct sample s;

    for (;;) {
        k_msgq_get(&sample_q, &s, K_FOREVER);
        printk("seq=%u value=%d\n", s.seq, s.value);
    }
}

K_MSGQ_DEFINE( name, msg_size, max_msgs, align ) allocates the buffer statically. The producer's k_msgq_put() with K_NO_WAIT never blocks and returns non-zero when the queue is full, as the example handles. With the reader waiting, the output is:

Text
seq=0 value=10
seq=1 value=20
seq=2 value=30

Each value is ten times the sequence number plus one, so the first message carries seq=0 and value=10.

Other queues. k_fifo and k_lifo pass pointers to items you allocate, with the kernel using the first word of each item for linking; k_pipe streams bytes; k_mbox exchanges messages with rendezvous. Start with message queues and semaphores.

Events. k_event provides a 32-bit set of event bits that threads can wait on in combination, like FreeRTOS event groups.

Timers and the work queue

A kernel timer calls a function when it expires, once or periodically. The callback runs in interrupt context, so it must be short and must not block:

timer.cc
static void tick_expired(struct k_timer *t)
{
    k_sem_give(&data_ready);
}

K_TIMER_DEFINE(tick_timer, tick_expired, NULL);

void start_timer(void)
{
    k_timer_start(&tick_timer, K_MSEC(500), K_MSEC(500));
}

k_timer_start( timer, duration, period ) starts a timer with an initial delay and a repeat period; a period of K_NO_WAIT makes it one-shot. The rule that the callback is an interrupt-level context matters: in FreeRTOS, a software timer callback runs in a task, and here it does not. Defer work to a thread, with a semaphore as above or with the work queue.

The work queue is a thread that runs queued work items. It is the answer to "I have something to do soon, outside an interrupt, and I do not want a thread of my own for it":

work.cc
static void do_work(struct k_work *w)
{
    printk("work item ran on the system workqueue\n");
}

K_WORK_DEFINE(my_work, do_work);

void from_isr_or_thread(void)
{
    k_work_submit(&my_work);
}

k_work_submit() puts the item on the system work queue, which runs the handler in a thread context. Delayable work, K_WORK_DELAYABLE_DEFINE with k_work_schedule(), runs it after a delay. A handler that takes a long time delays every other item on that queue, so keep handlers short, or create a dedicated work queue with its own thread for slow ones.

How an image boots

Knowing the order in which things start explains several beginner errors, such as a driver that is not ready when your code asks for it. After reset, the architecture's startup code sets up the stack and memory and calls the kernel's initialisation. The kernel then runs a sequence of initialisation levels, in a fixed order, calling every function registered at each level.

LevelWhat runs there
EARLYVery early hardware setup, before the kernel services exist
PRE_KERNEL_1Drivers with no dependencies on other devices, such as clocks and interrupt controllers
PRE_KERNEL_2Drivers that depend on those, such as a UART that needs a clock
POST_KERNELServices that need a running kernel, such as the logging thread
APPLICATIONApplication-level initialisation functions

Each device driver registers an initialisation function at one of these levels, with a priority within the level, through the macros that define the device. When the levels are done, the kernel creates the main thread, which calls main(), and the idle thread, and starts scheduling. Threads defined with K_THREAD_DEFINE and a start delay of 0 start at that moment.

The practical consequence is that by the time main() runs, every device whose driver is enabled and whose devicetree node is "okay" has been initialised. Your code should still check that a device is ready, because a driver may have failed to initialise, and device_is_ready() and gpio_is_ready_dt() exist for that. They return false when the node is disabled, the driver is not compiled in, or the init function reported an error, which is why they are the first line of nearly every sample.

You can register your own initialisation with SYS_INIT( function, level, priority ), for setup that must happen before main(), such as enabling a regulator on the board. Keep such functions short and avoid blocking, since the scheduler is not running at the early levels.

Interrupts and drivers from the application

Most of the time you use a driver through its API, and the API handles interrupts for you. A GPIO input with an interrupt callback is the typical case:

button.cc
#include <zephyr/kernel.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/sys/printk.h>

#define BUTTON_NODE DT_ALIAS(sw0)

static const struct gpio_dt_spec button = GPIO_DT_SPEC_GET(BUTTON_NODE, gpios);
static struct gpio_callback button_cb_data;

K_SEM_DEFINE(pressed, 0, 1);

static void button_isr(const struct device *dev, struct gpio_callback *cb, uint32_t pins)
{
    k_sem_give(&pressed);
}

int main(void)
{
    if (!gpio_is_ready_dt(&button)) {
        return 0;
    }
    gpio_pin_configure_dt(&button, GPIO_INPUT);
    gpio_pin_interrupt_configure_dt(&button, GPIO_INT_EDGE_TO_ACTIVE);
    gpio_init_callback(&button_cb_data, button_isr, BIT(button.pin));
    gpio_add_callback(button.port, &button_cb_data);

    for (;;) {
        k_sem_take(&pressed, K_FOREVER);
        printk("button pressed\n");
    }
}

The sequence is the one every Zephyr peripheral follows: check the device is ready, configure it from the devicetree spec, register a callback, and handle the event in a thread. The callback runs in interrupt context, so it does the least possible, here giving a semaphore, which is allowed from an interrupt. The thread does the work. Pressing the button on the board, aliased as sw0, prints:

Text
button pressed

For mechanical buttons, the example has no debounce, so one press may print more than once; add a short sleep after the take, or a delayable work item, as an exercise.

For code of your own that needs a raw interrupt, IRQ_CONNECT and irq_enable exist, with architecture-specific details. It is rarely necessary at the application level, since the driver APIs cover the peripherals, and the interrupt-related rules matter more: in an interrupt handler, do not block, do not call functions that sleep, and use only the kernel calls documented as ISR-safe, such as k_sem_give(), k_msgq_put() with K_NO_WAIT, and k_work_submit().

Reading what the build tells you

A large share of early Zephyr problems are build-configuration problems, and the build leaves evidence. Keep this table of where to look.

SymptomLook atWhy
A CONFIG_ option has no effectbuild/zephyr/.config and the build warningsA dependency is unmet and the option was dropped
DT_ALIAS or node macro fails to compilebuild/zephyr/zephyr.dtsThe alias or label is not in the final tree
A device is not readyThe node's status in zephyr.dts, the driver's KconfigThe node is disabled or the driver not enabled
Image too big for flashwest build -t rom_reportShows which symbols take the space
RAM overflow at linkwest build -t ram_reportSame for RAM
Wrong pin or peripheralThe board's .dts and your overlayThe overlay may not have been applied
Overlay seems ignoredThe file name and location, and -DDTC_OVERLAY_FILE if setThe overlay must be app.overlay or boards/<board>.overlay

The configuration used in a build can be overridden on the command line with -D arguments to CMake, for instance west build -b nucleo_f401re my_app -- -DOVERLAY_CONFIG=extra.conf, which merges another Kconfig fragment, and -DDTC_OVERLAY_FILE=extra.overlay for a devicetree overlay. These are handy for trying a change without editing files, and are the way continuous integration builds variants.

Sizing threads and choosing priorities

Zephyr gives you the same two choices as any RTOS, how big each stack is and what priority each thread has, with a few tools that make them easier to get right.

For stacks, start generous, such as 1024 to 2048 bytes for threads that log or format text, and measure with the thread analyser shown earlier. Reduce them only when the analyser shows large unused space after running the worst-case workload. Enable stack overflow protection while developing: CONFIG_HW_STACK_PROTECTION=y on cores with an MPU or stack limit register faults at the overflow, and CONFIG_STACK_SENTINEL=y is a software check on context switch. Logging and printk with floating-point formats use more stack, and the main thread's stack is set by CONFIG_MAIN_STACK_SIZE.

For priorities, keep the scheme simple. A reasonable arrangement is: interrupt handling is done in the interrupt, deferred work in the system work queue or a high-priority thread, protocol and control threads at middle priorities, and logging, housekeeping and long computations at low priorities, remembering that low priority means a larger number. Avoid cooperative priorities until you have a reason, since a cooperative thread that does not yield starves everything below it. Document the priority table in the source, in one place, so the relationships are visible.

Modules, west and your own repository

A real project is not a copy of the samples. Zephyr's workspace model has a pattern for that: your application lives in its own git repository, with a west.yml manifest that names the Zephyr version it needs and any extra modules, and west init -l (local manifest) makes a workspace around it. Your repository is then the manifest repository of the workspace, and west update fetches Zephyr at the version you pinned and the modules you listed. This is the structure the project calls a T2 topology, and the documentation describes it in the application development section.

The benefit is that your application, its dependencies and the exact Zephyr revision are versioned together, so a clean checkout builds the same thing on any machine. For a first experiment, an application directory inside the workspace, as earlier in this guide, is simpler; move to a manifest repository when the project grows beyond one developer or one machine.

Vendor code, such as hardware abstraction layers, comes in as modules, which are additional repositories listed in the manifest and built into the image when the corresponding Kconfig option is on. That is why west update takes a while: it fetches the modules for many vendors, even ones you do not use. A manifest name-allowlist or group filter can limit it, described in the west documentation.

Power, time and the system clock

Two more concepts appear early in real projects. The kernel's clock ticks at CONFIG_SYS_CLOCK_TICKS_PER_SEC, a configuration value that a board may set, and timeouts such as K_MSEC(5) are converted to ticks at compile time. Because the tick rate may be much higher than 1 kHz on some boards, a delay of one tick is a short time, not a millisecond; use the K_MSEC, K_USEC and K_SECONDS macros and convert, not raw tick counts.

Zephyr's kernel is tickless by default on most architectures, with CONFIG_TICKLESS_KERNEL enabled: the system timer is reprogrammed to the next timeout, not run at a fixed rate, so an idle system sleeps for as long as the next timeout allows. Power management, with the policy for choosing a low-power state when the system is idle, is a separate subsystem, CONFIG_PM, that you enable and tune per product. It uses the same timeout information that the tickless kernel computes. The details of the states depend on the SoC, so read the power management documentation for yours when you reach that stage.

Logging

printk() is for early or simple output, and the logging subsystem is for the application. It gives levels, module names, deferred formatting, and compile-time filtering. Enable it in prj.conf and use it in code:

prj.confText
CONFIG_LOG=y
log_use.cc
#include <zephyr/logging/log.h>

LOG_MODULE_REGISTER(app, LOG_LEVEL_INF);

int main(void)
{
    LOG_INF("started, tick rate %d", CONFIG_SYS_CLOCK_TICKS_PER_SEC);
    LOG_WRN("battery low: %d mV", 3100);
    LOG_DBG("not printed at INF level");
    return 0;
}

The macros are LOG_ERR, LOG_WRN, LOG_INF and LOG_DBG. Each message is tagged with the module name and level, and prefixed with a timestamp. The output on the console:

Text
[00:00:00.004,000] <inf> app: started, tick rate 10000
[00:00:00.004,000] <wrn> app: battery low: 3100 mV

The tick rate value depends on the board and configuration. The debug line is absent because the module's level is LOG_LEVEL_INF. By default, logging is deferred, formatting happens in a low-priority thread, and a message from an interrupt costs little. This is a significant difference from FreeRTOS, where logging is whatever you build.

Memory

Zephyr's kernel objects are static by default, defined with macros that place them in RAM at link time. Your application's stacks are static arrays. The kernel provides a heap for dynamic allocation, k_malloc() and k_free(), and its size is CONFIG_HEAP_MEM_POOL_SIZE; with the value 0, there is no heap and k_malloc() returns NULL. The main thread's stack size is CONFIG_MAIN_STACK_SIZE. Thread stack overflow detection is available through CONFIG_STACK_SENTINEL or hardware stack protection options where the architecture offers them, with CONFIG_HW_STACK_PROTECTION using the MPU's guard region on supported cores.

The memory usage is printed at the end of each build, as in the blinky post, and the west build -t ram_report and rom_report targets give a per-symbol breakdown in a table. Run them when a build is bigger than expected. For stack usage at run time, CONFIG_THREAD_ANALYZER=y provides a report of each thread's stack use:

prj.confText
CONFIG_THREAD_ANALYZER=y
CONFIG_THREAD_ANALYZER_AUTO=y
CONFIG_THREAD_ANALYZER_AUTO_INTERVAL=5
CONFIG_THREAD_NAME=y

It prints a line per thread with the stack used and the total, which is the equivalent of reading FreeRTOS high-water marks.

Debugging and the shell

For a hardware debug session, west debug starts the board's debug server and a GDB session:

debug.shShell
west debug

For the Nucleo board, west starts OpenOCD with the board's configuration and attaches GDB to it, with zephyr.elf loaded. Set breakpoints on your functions as usual. Zephyr's thread awareness in a debugger depends on the debug tool; with CONFIG_DEBUG_THREAD_INFO=y the kernel records the information a thread-aware debugger can use.

The shell is a command-line interface over the console. Enable it with CONFIG_SHELL=y and, for kernel commands, CONFIG_KERNEL_SHELL=y:

prj.confText
CONFIG_SHELL=y
CONFIG_KERNEL_SHELL=y
CONFIG_THREAD_MONITOR=y

Connect a terminal at the console's baud rate and type commands such as kernel threads to list threads, kernel stacks for stack usage, and kernel uptime. You can register your own commands, which makes the shell the place to expose diagnostics, test hooks and configuration on a bench device.

Testing

Zephyr's test framework is ztest, and its test runner is twister. A test is a small application with test cases:

test_math.cc
#include <zephyr/ztest.h>

ZTEST_SUITE(math_suite, NULL, NULL, NULL, NULL, NULL);

ZTEST(math_suite, test_add)
{
    zassert_equal(2 + 2, 4, "arithmetic is broken");
}

Twister builds and runs tests across a set of platforms from a description file, testcase.yaml. For fast iteration, the native_sim board compiles the application and the kernel as a program for the host, so tests run on the development computer without hardware, using simulated peripherals where they exist. That is the quickest loop for logic that does not depend on real hardware. Tests of drivers and timing still need the board.

Comparing with FreeRTOS

If you know FreeRTOS, this table maps the common ideas.

ConceptFreeRTOSZephyr
TaskTask, xTaskCreate()Thread, K_THREAD_DEFINE() or k_thread_create()
Priority orderHigher number is higher priorityLower number is higher priority
Cooperative schedulingWhole kernel optionPer-thread, by negative priority
SleepvTaskDelay()k_msleep()
QueuexQueueCreate(), copies itemsK_MSGQ_DEFINE(), copies items
Binary semaphorexSemaphoreCreateBinary()K_SEM_DEFINE( s, 0, 1 )
Software timer callbackRuns in the timer taskRuns in interrupt context
Deferred workTimer pend-function or a taskWork queue
ConfigurationFreeRTOSConfig.hKconfig
Hardware descriptionIn code and vendor HALDevicetree
Stack size unitsWords (bytes on ESP-IDF)Bytes
AllocationHeap implementationsStatic by default; optional kernel heap

Three differences cause real bugs. The priority direction is reversed. The timer callback context is different, so a callback that does work valid in a task, such as locking a mutex, is wrong here. And the hardware description is separate from the code, so a missing devicetree property or Kconfig option, not a code mistake, is often the cause of a peripheral that does not work.

Mistakes almost everyone makes once

A short list, from the problems that fill the forums, each with the cause so you can recognise it.

Configuring in menuconfig and losing the change. The menu edits the build directory only. A pristine rebuild starts again from prj.conf. Put every setting you want to keep in the file.

Forgetting to enable the driver. The devicetree node says the hardware exists, and the Kconfig option says the driver is built. A sensor that does not respond is often missing CONFIG_SENSOR=y or its driver option, and the build does not complain.

Assuming higher numbers mean higher priority. They do not. A thread at priority 10 is below a thread at priority 2.

Blocking in a timer callback or an interrupt handler. These run in interrupt context. Calling k_msleep() or taking a mutex there is an error, and with assertions enabled the kernel reports it.

Returning from a thread entry that should run forever. A thread that returns ends, and its stack is released for reuse. That is legal and often a surprise when a worker thread stops after the first loop pass because of an early return.

Using a stale build directory after changing boards. Switching -b without -p always can leave configuration from the previous board. When in doubt, build pristine.

Mixing up the main thread and the application. main() is optional. A Zephyr application can run entirely from static threads, timers and callbacks, and main() can return immediately, as the thread example shows.

Ignoring the warnings from Kconfig. An unmet dependency prints a warning and continues. The image builds and does not do what you configured.

Choosing Zephyr

Zephyr is a good fit when you need many boards or chips from one codebase, a rich set of middleware such as Bluetooth Low Energy, USB, networking or file systems already integrated, long-term maintenance through a community, and a hardware model that separates application from board. It is a heavier fit for the smallest parts, and for projects where you want complete control over every component and a minimal footprint. It asks more of a newcomer than FreeRTOS does, and returns more once you are inside its model.

A path to learn it

An order that works:

  1. Build and flash the samples samples/basic/blinky and samples/hello_world on your board.

  2. Read the blinky source and the board's devicetree file until the DT_ALIAS chain is clear.

  3. Write your own application with two threads and a semaphore.

  4. Add a message queue and a timer; print with logging instead of printk().

  5. Add a devicetree overlay that enables a peripheral, and a Kconfig fragment for its driver.

  6. Add the shell and the thread analyser.

  7. Write a ztest suite and run it on native_sim.

  8. Read the documentation sections on the subsystems your product needs.

When this guide does not apply

The guide describes Zephyr 4.1 and its SDK 0.17. Zephyr releases roughly three times a year, and board names, hardware model details and some configuration options change between releases; the board naming uses the hardware model version 2 introduced in 4.0, in which a board may have qualifiers after a slash. The commands and configuration given are the ones in the official getting started guide for that release, and the sample outputs are illustrative of format and not of any specific build's numbers. If your board is not in the supported list, adding it means writing its devicetree and board files, which is a project of its own covered in the documentation.

Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.