One devicetree line moves a blinking LED to another pin. One Kconfig line decides whether a driver exists at all. See how Zephyr turns small text files into a firmware image.
Learn the six tools every Zephyr project uses: west, devicetree, Kconfig, the driver model, logging and the sensor API. Then compare the result with bare metal.
Pick a board, then change what the name led0 points to. The C code stays the same. Watch the build accept the change, or fail. Then we build, piece by piece, each tool that made that happen.
You need the idea of a register and a pin (see RTOS under the hood) and a driver written by hand (see From register map to driver). We build the rest from zero.
There are no course slides for this lesson. It is built from the primary sources: the Zephyr documentation and source tree, the Nordic Developer Academy (nRF Connect SDK Fundamentals), the Memfault Interrupt series Practical Zephyr, and the Golioth Zephyr training. Every idea is re-taught here in our own words and devices.
A model, not a build: the board facts (gpio0 pin 13 and 14, active low, on the nRF52840 DK; gpioa pin 5, active high, on both Nucleo boards, one LED each) come from the board files in the Zephyr tree. The error wording for the missing label is a gist; the missing-alias error is the one the blinky sample page quotes.
Chapter 0
See what you rewrite when a board, a sensor or a rule changes, and why a framework moves most of that work out of your C
You blink an LED on one board. The code writes a bit in a GPIO register, waits, and writes it again. It works. Next month the company picks a different chip. The new chip has other registers, a different clock tree and its LED sits on another pin.
Every line that touched a register is now wrong. Your logic is fine, but it is buried under hardware details. This is the usual pain of bare-metal firmware (code that talks to the chip directly, with no operating system or framework between).
The pain grows with the product. A real device has a sensor on a bus, a radio, a log, a bootloader and three board revisions. Each part has to be written, connected and kept in step with the others. Teams solve this in the same way every time: they put the hardware facts in one place and the logic in another.
Zephyr is an open-source real-time operating system (RTOS) and framework, run as a Linux Foundation project. An RTOS is a small kernel that schedules tasks with known timing (see RTOS under the hood). Zephyr also ships drivers, a build system and a way to describe hardware as data.
That last part is the one to learn first. Zephyr splits a project into three kinds of file. Your C code says what the device does. A devicetree says what hardware exists and how it is wired. A Kconfig file says which software features to build in. A tool called west fetches the source and runs the build.
The Zephyr docs put the split in one sentence: devicetree mainly deals with hardware, and Kconfig with software. Keep that sentence. Chapter 2 returns to it, and most Zephyr mistakes are a fact in the wrong file.
Picture the firmware as a stack of five layers. At the top is your application logic: read a sensor, decide, act. Under it sits the sensor driver, which knows one chip’s registers. Under that is the bus driver (I2C, SPI), which knows one microcontroller’s bus block. Then clock and pin setup. At the bottom are startup, linker script and vectors, the code from reset to main.
In bare metal you own all five. In Zephyr the bottom four come from the tree, selected by your board and your config. You still write the top layer. That is the whole bargain, and the device below lets you test it.
Pick a kind of change. Each column shows the five layers for one approach. A teal box needs only a config edit. A warm box needs new code. A grey box stays as it is.
Illustrative: this is the typical case when the new parts already have drivers in the Zephyr tree. A part with no driver needs new code in both columns. A new app rule touches the app layer either way, and the device shows that on purpose.
Look at the third choice first. A new application rule costs the same with or without Zephyr: you edit your own code. A framework does not make your logic easier. It makes the hardware changes cheaper.
Now look at the first choice. In bare metal, a new chip means new bus code, new clock and pin code, and new startup code. In Zephyr, a new board is a set of board files in the tree, and your app keeps its calls to the same functions.
The bargain has a cost, and the cost is learning. Zephyr has its own build tool, its own two configuration languages and its own driver model. A blink that takes ten lines of register code takes a workspace, a board name and a devicetree alias. The first week feels slow.
It also costs flash and RAM, since the kernel and drivers are real code. A tiny part with 16 KB of flash may not fit it. Chapter 9 sorts out when each approach wins.
In the hero you already used the idea. You changed one alias and the same C line bound to another pin. That worked because the line asks the question “where is led0?” and the devicetree answers it for each board.
Chapter 1
Follow a project from an empty folder to a flashed board, and see why the source of a Zephyr app lives in many repositories at once
A new teammate joins on Monday. Their laptop is empty. You say: “Clone the app and build it.” An hour later the build fails with a missing header from a vendor library that nobody told them about.
The app needs the Zephyr kernel, a hardware library for the chip, a bootloader and a crypto library. Each lives in its own Git repository, each at one exact version. Cloning your app repo gives them none of it. Something must know the list and fetch it.
That something is west. The Zephyr docs call it a “swiss-army knife command line tool”. It does two jobs. It manages many Git repositories as one unit, and it wraps the build, flash and debug steps so that you type the same commands on every board.
A workspace is one folder that holds all the repositories. Its top is called the topdir. West finds it by looking for a hidden folder named .west and using the parent of that folder. The docs show this layout:
workspacezephyrproject/ # topdir (the name is arbitrary) ├── .west/config # local, per-workspace settings ├── zephyr/ # the manifest repository: holds west.yml ├── modules/lib/zcbor/ # one example project └── tools/net-tools/ # another
The list of repositories is the manifest, a YAML file named west.yml by default. It names each project (a Git repository), where to get it and which revision (a tag, branch or commit) to use. The repository that holds west.yml is the manifest repository. Every workspace has exactly one.
The manifest repository can be Zephyr itself, as in the layout above. It can also be your own app repository, which then lists Zephyr as a dependency. The second form is common in products, since your app, not Zephyr, owns the version choice. Memfault’s Practical Zephyr series builds that form step by step.
Most days you use four commands. Step through them in the device below. The first command creates the workspace:
shellwest init -m https://github.com/zephyrproject-rtos/zephyr --mr v2.5.0 zephyrproject
The docs example reads like this. -m gives the manifest repository to clone. --mr gives the revision of it. The last word names the new folder. west init creates .west/config and clones the manifest repository. It does not fetch the other projects.
The second command fetches them. In the docs’ words, west update “initially clones, and later updates, the projects listed in the manifest”. It reads .west/config to find the manifest, then clones what is missing and moves existing projects to the listed revision. Run it again whenever you check out a different revision of the manifest repository.
The third and fourth commands build and flash. The blinky sample page gives the form: west build -b reel_board samples/basic/blinky, then west flash. The -b flag names the board. Change the name and the same app targets another board. In Zephyr 3.7 and later a board target can carry a chip qualifier, such as nrf52840dk/nrf52840.
Press Next to run the next command. The panel shows what appears on disk. Then switch the tag pin on and off and read what changes.
A model of the workspace, not a real checkout. The module list is illustrative (four projects); a real Zephyr manifest lists many more. The build folder names (build/zephyr/zephyr.elf, zephyr.hex, zephyr.bin, zephyr.dts, .config) are the usual ones.
Say the manifest lists the chip’s hardware library with revision: main. On Monday you run west update and get commit A. On Wednesday the library maintainers push commit B, which renames a register macro. Your teammate runs west update and gets B. Same app, same board, different headers.
The symptom is a build that passes on your laptop and fails on theirs, or worse, builds on both and behaves differently. The measurement is west list, which prints each project with its path and revision. Two lists that differ on one line show you the culprit in seconds. The fix is to name a tag or a full commit in west.yml, commit that file, and run west update again. Now the manifest is the single answer to the question “which source built this image?”.
This is also the reason to keep the manifest in your app repository. A release tag on the app then fixes the whole tree below it, and a build from that tag next year fetches the same source.
West is not the build system. Under west build sits CMake, which finds the board, the devicetree and the Kconfig files. West calls it and tidies up the options. The next chapter follows that hand-off.
On real hardware. With an nRF52840 DK, run the four commands on the blinky sample. In the sample the LED toggles every 1,000 ms (its SLEEP_TIME_MS). Probe the LED pin, P0.13, with a logic analyzer. You should see a square wave with a 2,000 ms period. Then change the board name and confirm that a different pin toggles.
west update on different days. What do you check first?Chapter 2
Sort every setting into hardware or software, and follow the files the build writes from your text
You want to change the baud rate of a serial port to 230,400. You open the project and find three places that mention the UART: a board file, a prj.conf and a C file. Which one do you edit?
If you guess wrong, nothing warns you. The build passes. The port stays at the old rate, or the driver is missing and your printk goes nowhere. A large share of beginner Zephyr bugs are a correct fact in the wrong file.
The way out is a rule. The Zephyr docs state it in one line: devicetree mainly deals with hardware, and Kconfig with software. The docs’ own UART example shows both halves.
The UART hardware is described by a devicetree node. The node gives the compatible string that names the kind of block, and reg, the address of its registers. Boot-time settings, such as the baud rate (current-speed) and the interrupt priority, also go in the node.
Whether the UART driver code is built into the image is a Kconfig choice. An application that never uses the UARTs can leave the driver out, even though the board’s devicetree still lists the UART nodes. The hardware exists whether you use it or not. The code costs flash only if you ask for it.
So the baud rate is a hardware fact about this board and this port: it goes in devicetree. The switch for the serial driver is software: it goes in Kconfig. Your C code does neither. It reads both through generated names.
Neither language is read by the compiler. The build turns each into C first. Take devicetree. Its inputs are four kinds of file: .dts sources (one per board), .dtsi includes (shared SoC descriptions), .overlay files (your changes) and .yaml bindings (rules for what a node may contain, Chapter 6). The C preprocessor runs over the text files first. The board file and then your overlays are joined, with overlays last so they can override the board.
The outputs land in the build folder. zephyr/zephyr.dts is the final merged tree, the best file to open when something looks wrong. zephyr/include/generated/zephyr/devicetree_generated.h holds the macros your C code reads. You never include that header directly. You include devicetree.h and use names like DT_ALIAS.
Kconfig has a matching path. Its inputs are the Kconfig files that declare symbols and dependencies, and the value files: the board’s defconfig and your prj.conf. Values merge in order: the board defconfig, then CONFIG_ entries on the command line, then the application files. The merged result is zephyr/.config. From it the build writes autoconf.h, which holds the CONFIG_ macros. Code for a feature that is off is compiled out.
The languages are not sealed from each other. The build makes a file called Kconfig.dts. For every compatible string that a binding knows, it creates a hidden switch named DT_HAS_<COMPATIBLE>_ENABLED. The switch is true when at least one node with that compatible has status = "okay".
Drivers depend on that switch. A sensor driver declares depends on DT_HAS_VENDOR_CHIP_ENABLED, and usually default y. The effect: you add a sensor node to the devicetree, and its driver switches on by itself. Remove the node and the driver disappears from the image. Hardware drives software, in one direction.
Try it. Pick a file you might edit and see which outputs the build must regenerate.
Pick a file on the left. Solid lines go to outputs that always change. Dashed lines change only when the edit flips a setting the other language reads.
The file names and the generated paths come from the Zephyr build documentation. The dashed link from devicetree to .config is the DT_HAS symbol described above. Which outputs a given edit really changes depends on the edit; this shows the possible reach.
Notice main.c. It reaches only the final image. A devicetree edit can reach almost everything, and that is why a one-line overlay can add a driver, change a pin and change the binary size at once.
Your board has an I2C sensor node with status = "disabled". You write an overlay that sets status = "okay".
compatible = "bosch,bme280" and makes DT_HAS_BOSCH_BME280_ENABLED true.depends on that switch and defaults to y, so it turns on. The I2C driver turns on too, since the BME280 driver selects it.The failure mode runs the other way. Symptom: you add CONFIG_BME280=y to prj.conf and the device is still missing at run time. Measurement: open build/zephyr/zephyr.dts and find the node. If it says status = "disabled", the dependency was never true. Fix: enable the node in an overlay. Chapter 5 returns to this with a device.
On real hardware. On any board, build the blinky sample, then open build/zephyr/zephyr.dts and build/zephyr/.config. Search for the LED node and for CONFIG_GPIO. Now add an unused sensor node in an overlay and rebuild. Check which of the two files gained lines.
Chapter 3
Read a board file as a tree of nodes, and learn the four ways C code names one of them
Open the blinky sample and read its only interesting line. It asks for something called led0. Your board has an LED soldered to some pin. The sample does not say which pin, which port, or whether the pin is lit by a high or a low voltage.
Somebody wrote those facts down. They are not in C. They are in a file called the devicetree: a text description of the hardware, shaped as a tree. Linux uses the same idea for the same reason, and the embedded Linux lesson meets it from the kernel side. In Zephyr it also carries boot-time settings, so it is both a description language and a configuration language.
A node is one thing in the hardware: a serial port, a GPIO bank, an LED. A property is a named fact about it, such as an address or a speed. Nodes nest. The LED node sits inside a leds node, the way a file sits in a folder. The path of a node is its folder names joined by slashes.
Here is the real LED node from the Zephyr board file for the nRF52840 DK:
devicetreeleds { compatible = "gpio-leds"; led0: led_0 { /* label: node-name */ gpios = <&gpio0 13 GPIO_ACTIVE_LOW>; /* port, pin, flags */ label = "Green LED 0"; }; };
Read it slowly. led0: is a label, a short handle for the node that follows. The node’s real name is led_0. The gpios property holds three cells: a reference to the GPIO port node (&gpio0, a phandle, which is a pointer between nodes), pin number 13, and a flag saying the LED lights when the pin goes low. The sentence is: “this LED is on port 0, pin 13, active low”.
C code needs a handle on a node. Zephyr gives four, and each is a macro in devicetree.h:
DT_NODELABEL(led0), by the label. Short, but labels belong to the board author.DT_ALIAS(led0), by an entry in the aliases node. This is the portable one. Samples ask for aliases, and every board maps the alias to its own node.DT_CHOSEN(zephyr_console), by an entry in the chosen node. It answers a role question: which UART is the console?DT_PATH(soc, uart_40002000), by the full path. Fragile, since addresses change between chips.Why an alias? The board author writes led0 = &led0; once. Now any app, on any board, can say DT_ALIAS(led0). The name is a contract between app and board. The hero showed it: when you deleted the alias, the contract broke and the build stopped.
Every node you will meet carries some of these. compatible names the kind of hardware and picks the driver (Chapter 6). reg gives the register address and size, and it is why a node name carries an address: uart@40002000. status says whether the node is in use: "okay" or "disabled". Properties like current-speed = <115200> hold settings. References such as pinctrl-0 = <&uart0_default> point at other nodes.
Names change on the way to C. Lowercase letters and dashes become underscores in macro names. The docs show current-speed read as current_speed and vnd,serial as vnd_serial. Dashes cannot appear in C names, so the build rewrites them.
Pick a node. The panel shows its source and which C names reach it. Press the status button to see how an overlay changes the answer.
Property values for led0, button0 and uart0 are read from the Zephyr board file for the nRF52840 DK. The I2C0 node is shown as the SoC file leaves it, disabled. The nRF52840 DK board file already sets i2c0 to okay, so on that kit an overlay with this line changes nothing. It shows the mechanism. Addresses are the nRF52840 peripheral addresses.
cstatic const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(DT_ALIAS(led0), gpios);
DT_ALIAS(led0) looks in aliases, finds led0 = &led0, and yields the node led_0.GPIO_DT_SPEC_GET(node, gpios) reads that node’s gpios property: port gpio0, pin 13, flag active-low.gpio_dt_spec with three fields: the device pointer for gpio0, the pin (13) and the flags. All of it is fixed at compile time. No lookup happens at run time.gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE) makes the pin an output and sets it to its logical active level. Because the flag says active-low, that is a physical 0 V.That last step is a small gift. Your code says “on”. The devicetree knows the board lights the LED with a low pin. On the Nucleo boards the flag is active-high, and the same code drives 3.3 V.
The symptom is a compile error at the GPIO_DT_SPEC_GET line: ‘__device_dts_ord_DT_N_ALIAS_led_P_gpios_IDX_0_PH_ORD’ undeclared. The blinky page quotes it, and it means “this board has no led0”. The measurement is a search of build/zephyr/zephyr.dts for led0. If the alias is missing, the board does not define it. The fix is an overlay that adds aliases { led0 = &your_led_node; }; to the root node, which Chapter 4 does.
On real hardware. Build blinky for an STM32 Nucleo and open zephyr.dts. Find the led0 alias and read which pin it names (PA5 on the F446RE and L476RG). Probe that pin and confirm that it goes high when the LED lights.
DT_ALIAS(led0). It builds for board A and fails for board B with an “undeclared” error on that line. What is the most likely cause?Chapter 4
Change a board’s hardware description without editing the board, and move a signal to another pin without breaking sleep
Your sensor board arrives with the I2C clock wire on a different pin from the dev kit. You must move the bus. You could edit the board file inside the Zephyr tree. That works until the next west update replaces the file, or a teammate asks which of your changes live in Zephyr.
The answer is an overlay: a small devicetree file in your app that is joined to the board file at build time, after it. Where both say something about the same node, the overlay wins. Your change stays in your repository and the board stays untouched.
If you set nothing, the build looks in your app folder for these files in order, per the docs: socs/<SOC>_<QUALIFIERS>.overlay, boards/<BOARD>.overlay, a revision-specific form, <BOARD>.overlay, and finally app.overlay. The Nordic Developer Academy teaches the board-named file in a boards folder, for example boards/nrf52840dk_nrf52840.overlay. To choose files yourself, set the CMake variable DTC_OVERLAY_FILE. EXTRA_DTC_OVERLAY_FILE adds files with higher priority.
The syntax repeats one trick. To change an existing node, refer to it by label with an ampersand and write only the properties you change:
devicetree/* boards/nrf52840dk_nrf52840.overlay */ &i2c0 { status = "okay"; /* turn the node on */ }; / { aliases { led0 = &led1; /* point an alias somewhere else */ }; };
Read the two blocks in that overlay. The first, &i2c0, says “find the node with the label i2c0 and set its status to okay”. The second starts at the root, /, and adds an entry to the aliases node. This is the hero’s trick: the app still asks for led0, and the alias now leads to the second LED. You changed which LED blinks without touching one line of C.
Overlays can also delete. The line /delete-property/ led0; inside aliases removes the alias, which is how the hero produced its build error. You will rarely want that, but it shows that the overlay has the last word.
Which physical pin carries which signal is not a property of the I2C node itself. A modern microcontroller can route most peripheral signals to many pins through a pin multiplexer (pinmux): a switch matrix inside the chip. Zephyr keeps that choice in its own subsystem, pin control (pinctrl).
The pattern has three parts. A peripheral node says pinctrl-0 = <&uart0_default>; and pinctrl-names = "default", "sleep";. Each pinctrl-N is a state, and the names label them. The two standard states are default (normal operation) and sleep (low power). A node in the &pinctrl group lists the pins for each state.
This is the real UART state for the nRF52840 DK, from the Zephyr tree: TX on port 0 pin 6 and RTS on pin 5 in one group, RX on pin 8 and CTS on pin 7 in another, with a pull-up on the inputs. The I2C0 default state is SDA on pin 26 and SCL on pin 27. On Nordic chips a pin is written NRF_PSEL(TWIM_SDA, 0, 26): signal, port, pin.
At start-up the driver calls pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT). That one call is the whole pin setup. No line of your code writes a pin register. When the device is suspended for power saving, the driver applies the sleep state instead.
Port 0 has 32 pins. Slide SDA and SCL to new pins. Pins used by the board’s UART, LEDs and buttons are marked. Teal pins are yours.
Pin uses are read from the nRF52840 DK board files in the Zephyr tree: UART on P0.05 to P0.08, LEDs on P0.13 to P0.16, buttons on P0.11, P0.12, P0.24 and P0.25, and the default I2C0 pins P0.26 and P0.27. Other pins on a real board can be taken too (crystals, NFC, reset), so check the board documentation. This is a model of the overlay, not the build.
Say you move SDA to P0.13 on the DK. The slider shows the clash: P0.13 is already led0. The build is happy, because two nodes naming one pin is not a devicetree error. At run time both drivers configure the same pin, and the last one to start wins. The LED flickers when the bus talks, and the bus sees garbled bits.
Now pick a free pin pair, such as P0.30 and P0.31, and turn the sleep switch off. The overlay changes only the default state. The sleep state still names P0.26 and P0.27. The Nordic Academy lesson on changing a SPI pin makes the same point: both the default and the sleep state need the edit. Without it, a device that sleeps puts your new pins in a different mode from the one it uses awake, and configures pins you no longer use.
The failure shows up late. The symptom: the sensor works at the bench and draws too much current in the field after the first sleep. The measurement: a power profiler trace, compared with the sleep state in zephyr.dts. The fix: edit both states.
On real hardware. On the nRF52840 DK, move I2C0 to P0.30 and P0.31 and put a logic analyzer on those two pins while the app reads the sensor. You should see clock edges at the bus speed you set (100 kHz in standard mode) on the new pair and nothing on P0.26 and P0.27.
default pinctrl state. What is the risk?Chapter 5
Learn why a setting in prj.conf can be silently ignored, and read the warning that proves it
You want to read a BME280 temperature sensor. You add one line to prj.conf: CONFIG_BME280=y. The build passes. You flash the board. The app prints “Error: no device found.” and stops.
The line did nothing, and nobody told you. Or somebody did, in a warning that scrolled past during the build. To see why, you need the rules of the second language, Kconfig. It is the same system the Linux kernel uses to choose its features.
A Kconfig symbol is one named setting. Most are booleans (y or n). Some hold a number or a string. Symbols are declared in files named Kconfig, spread through the Zephyr tree, and each declaration can carry rules. Your job is to supply values.
The values come from files, merged in a fixed order. Per the docs, the board’s _defconfig goes first, then any CONFIG_ entries given on the command line, then your application files, with prj.conf as the default. When a symbol is set twice, the later source wins, so your prj.conf beats the board default. The merged result is written to zephyr/.config in the build folder, and from it the build writes autoconf.h. Your C code tests those macros, and the preprocessor drops the code of anything that is off.
A prj.conf is plain text, one assignment per line: CONFIG_I2C=y, CONFIG_MAIN_STACK_SIZE=2048. Notice what it is: a request. The rules in the Kconfig files decide whether the request is granted.
Here is the head of the real BME280 declaration from the Zephyr tree, trimmed:
Kconfigmenuconfig BME280 bool "BME280/BMP280 sensor" default y depends on DT_HAS_BOSCH_BME280_ENABLED select I2C if $(dt_compat_on_bus,$(DT_COMPAT_BOSCH_BME280),i2c)
Read the four rules as sentences. default y: if nobody says otherwise, turn it on. depends on: it may only exist if the devicetree has an enabled BME280 node (Chapter 2). select I2C if ...: when it is on, it forces the I2C driver on, because the sensor sits on an I2C bus. The whole file is sourced under if SENSOR, so the sensor subsystem switch must be on too.
That gives two kinds of rule. depends on is a guard: the symbol cannot be turned on until its needs are met. select is a push: turning the symbol on forces another one on. A guard says no. A push says yes whether you like it or not. Both are what you want from a build system, until you are the one who typed the opposite.
Now the opening story is clear. Your CONFIG_BME280=y met a guard: either CONFIG_SENSOR was off, or no BME280 node was enabled. A guard that is unmet means the symbol stays n, and Kconfig prints a warning that says so. The docs describe it: assignments to symbols whose dependencies are not satisfied produce a warning. Warnings about assigning a symbol that does not exist stop the build.
Set KCONFIG_WARNING_AS_ERROR=y and every Kconfig warning becomes an error, so a dropped setting breaks the build on the day it is added, not weeks later. Use the toggles below to start the fight.
Each button is a line you could add. Aim for a BME280 driver that is on and a warning list that is empty. Then try turning I2C off by hand.
A model of three real rules from the Zephyr tree: BME280 depends on DT_HAS_BOSCH_BME280_ENABLED and sits under SENSOR, and it selects I2C on an I2C bus. The warning wording is the usual Kconfig style and varies a little between Zephyr versions.
CONFIG_BME280=y only. The node is not enabled and SENSOR is off. BME280 needs both, so it becomes n. The app finds no device.CONFIG_SENSOR=y. One guard is met. BME280 is still n, because the devicetree guard is not.y, and its select turns I2C on. You never wrote CONFIG_I2C=y.CONFIG_I2C=n. The push wins: I2C stays y and a warning says you assigned n but got y.The measurement for any doubt is the file build/zephyr/.config. A line CONFIG_BME280=y means the driver is in. A line # CONFIG_BME280 is not set means it is out, whatever prj.conf says. The interactive tool west build -t menuconfig shows the same rules as a tree, with each symbol’s dependencies. The docs add that changes made there only go to .config, so copy what you want to keep into prj.conf.
On real hardware. On an nRF52840 DK with a BME280 breakout wired to I2C0, build the sensor sample, then read .config. Remove the overlay line that enables the node, rebuild, and watch CONFIG_BME280 flip to not set. Check the image size too: the driver code leaves the binary.
prj.conf says CONFIG_BME280=y. The generated .config says # CONFIG_BME280 is not set. What do you check first?Chapter 6
Follow a node from its compatible string to a live device object, and see what breaks when start-up runs in the wrong order
In the driver lesson you wrote a driver by hand: a struct for state, an init function, a read function, a call from main. Zephyr has the same parts. What changes is who creates them, who calls them and in what order.
You add a sensor node to your devicetree. At boot, the sensor driver wakes up and registers itself, with no line in your code that creates it. Two questions follow. How does the node find its driver? And what stops the driver from starting before the bus under it is ready?
The link is the compatible string. A binding is a YAML file that declares one compatible string and the properties a node of that kind may have. The docs’ smallest example:
yamlcompatible: "foo-company,bar-device" properties: num-foos: type: int required: true
A node matches the binding when its compatible matches the binding’s line. If a node lists several strings, the build tries them in order and uses the first binding that exists. That is how a node can be “a specific chip, or failing that, a generic part”. The real BME280 binding is compatible: "bosch,bme280", with sensor-device.yaml and i2c-device.yaml included, so the node gets the common bus properties for free.
The binding does two jobs. It checks the node: a required property that is missing is a build error, caught on your desk instead of at run time. And it tells the build which macros to generate. In the driver source the match is written once, as a lowercase string with underscores: #define DT_DRV_COMPAT bosch_bme280. Then DT_INST_FOREACH_STATUS_OKAY(init_fn) expands once for every enabled node with that compatible. Two sensors on one board means two instances from one driver.
The result of that expansion is a device: a C struct named struct device with four fields. name is its label. config is read-only data fixed at build time, taken from the node (the bus, the address, the pins). data is per-instance state in RAM, such as the last reading. api points at a table of functions, the driver’s implementation of its subsystem.
The api field is the clever part. The sensor subsystem defines the table once: fetch, get, set an attribute. Every sensor driver fills the same table. So app code that calls sensor_sample_fetch(dev) works for any chip, as long as it has a driver. This is the interface idea from object-oriented code, done in plain C and checked at build time.
Your app gets a device with DEVICE_DT_GET(node) and must then test it with device_is_ready(dev). Ready means the device was created and its init function succeeded. A device that failed to init exists but is not ready. The BME280 sample prints this exact hint when the check fails: “check the driver initialization logs for errors”.
Drivers start before main, in init levels. The docs define three. PRE_KERNEL_1 is for devices that depend only on the processor and SoC hardware. PRE_KERNEL_2 is for devices that depend on those. POST_KERNEL is for devices that need kernel services, and it runs in the kernel’s main task. Inside a level, a priority from 0 to 999 orders the work. Lower numbers start first.
A sensor on I2C needs the I2C driver ready. The I2C driver’s priority comes from the symbol I2C_INIT_PRIORITY, which defaults to KERNEL_INIT_PRIORITY_DEVICE. The sensor subsystem’s own symbol is SENSOR_INIT_PRIORITY, with a default of 90. Because 90 is later than the device default, the bus is up first.
Pick the compatible string in your overlay. Then slide the sensor’s init priority across the POST_KERNEL axis. The I2C bus starts at the blue mark.
The sensor default of 90 is the value of SENSOR_INIT_PRIORITY in the Zephyr tree. The I2C marker at 40 is illustrative: the real value is that of KERNEL_INIT_PRIORITY_DEVICE, which this lesson does not quote. A real board has dozens of init entries; two are drawn.
bosch,bme280, priority 90. The binding matches. Kernel start-up runs the I2C init (illustratively at 40), then the sensor init at 90. The sensor can talk on the bus. device_is_ready returns true.main runs, finds a dead device and prints the hint.bosch,bme208, a typo. No binding has that name. The node matches nothing, so no driver instance is made. The build still passes. The app asks for any BME280 and gets NULL.bosch,bme680. A different driver claims the node. The sensor API calls in your app still compile. But that driver speaks the BME680 protocol, so on a real BME280 chip the init would be expected to fail.The symptom of case 2 is a device that exists but fails device_is_ready. The measurement is the boot log with driver init errors visible (Chapter 7 shows how to see it). The fix is to depend on the bus’s priority rather than guess a number, so keep the default unless you have a reason.
On real hardware. On an nRF52840 DK with a BME280 on I2C0, set CONFIG_SENSOR_INIT_PRIORITY=10 and read the boot log. You should see the sensor init fail. Restore 90 and confirm it passes.
Chapter 7
Work out what one log line costs on a serial port, and choose between deferred and immediate logging with the arithmetic in hand
A motor loop runs every millisecond. You add a printk to see a sensor value each pass. The motor starts to stutter. You remove the print and it runs smoothly. The print was the cause.
The reason is wire time. A UART sends one byte at a time. At 115,200 baud with 8 data bits, no parity and 1 stop bit (8N1), each byte takes 10 bit-times, which is 10 ÷ 115,200 s, about 87 µs. A short line of 60 characters plus a line ending is 62 bytes. That is 5.4 ms on the wire. A loop with a 1 ms deadline cannot wait for that.
Zephyr’s logging subsystem replaces raw prints with a system. You write one macro per message, at one of four levels: error, warning, info or debug (numbered 1 to 4 in the source, with 0 meaning none). The macros are LOG_ERR, LOG_WRN, LOG_INF and LOG_DBG, and they take a printf-style format.
Each source file belongs to a module. One file registers it with LOG_MODULE_REGISTER(name, CONFIG_NAME_LOG_LEVEL), and the others in the same module say LOG_MODULE_DECLARE(name). The registration gives the module a name that prefixes its lines, and a level you set in prj.conf. Messages above the level are removed at compile time. They cost no flash and no time.
CONFIG_LOG=y is the global switch. A backend is the place the text finally goes. The tree has a UART backend (CONFIG_LOG_BACKEND_UART), an RTT backend (CONFIG_LOG_BACKEND_RTT) that sends text over the debug probe, and a network backend that sends syslog messages.
The mode decides who pays the wire time. Immediate mode (CONFIG_LOG_MODE_IMMEDIATE) processes each message in the caller’s context. The caller formats the text and pushes it out the backend, so the caller waits. The Kconfig help warns that this affects performance, for example in a high-priority interrupt. It uses more stack too.
Deferred mode (CONFIG_LOG_MODE_DEFERRED) is the default. The call only stores the message in a circular buffer and returns. A separate logging thread drains the buffer later and feeds the backend. The Kconfig help calls this the least impact on the application. In the current logger the buffer holds the format string’s address and the arguments, not finished text, so storing is cheap.
A third mode, CONFIG_LOG_MODE_MINIMAL, sends every message straight to printk, with no timestamps, prefixes or run-time filtering. It is the smallest, and for the smallest chips.
Deferred mode has a catch, and it is the same as every queue. The buffer has a size (CONFIG_LOG_BUFFER_SIZE, in bytes). If messages arrive faster than the backend drains them, the buffer fills. The Kconfig default, CONFIG_LOG_MODE_OVERFLOW=y, drops the oldest message to make room. Set it to n and the new message is dropped instead. The logger can tell its backends how many it dropped through log_backend_dropped().
A burst of 62-byte lines arrives for 1 second at 115,200 baud. Pick a mode and move the sliders. In immediate mode the bar is the time your code is blocked. In deferred mode the line is the buffer.
Wire time is exact arithmetic: 62 bytes × 10 bits ÷ 115,200 baud = 5.38 ms per line, so the port moves at most 185 lines per second. The buffer is counted in lines for clarity; the real symbol counts bytes, and a stored message is not the same size as its text. This is a model, not the Zephyr logger.
Take 120 lines per second, a 16-line buffer, deferred mode.
LOG_INF call returns almost at once.The failure mode in the field: the log is missing the very lines you need, the ones just before a fault. The symptom is a gap in the log. The measurement is the dropped count, or a GPIO toggled around the log call, seen on a logic analyzer. The fixes are a faster backend (RTT moves data over the debug link, far faster than 115,200 baud), a larger buffer, a lower level on noisy modules, or fewer lines. Do not log in an interrupt in immediate mode.
On real hardware. On an nRF52840 DK, set a GPIO high before a LOG_INF and low after it, in immediate mode on the UART backend. A logic analyzer should show a pulse near 5 ms for a 62-byte line. Switch to deferred and the pulse shrinks to a tiny fraction of that.
LOG_INF in an interrupt handler. Which setup is safest for its timing?Chapter 8
Read a temperature through the same two calls on any chip, and decode the number format that avoids floating point
Your product ships with one temperature sensor. The supplier runs short, and the next batch has a different part with different registers, a different resolution and a different bus address. Your app code reads the temperature in forty places.
If each place talks to the sensor’s registers, you rewrite forty places. If each place calls a function that means “give me the ambient temperature”, you rewrite none. The Zephyr sensor API is that function, plus a promise about units. The docs describe its goal: a way to uniformly read, configure and set up event handling for devices that take real-world measurements in meaningful units.
The stable API has two calls, and the split matters. sensor_sample_fetch(dev) tells the driver to talk to the chip. It is a blocking call. The driver reads the registers over the bus and stores the raw result in its own instance data. The header warns it is unsafe to call from an interrupt handler when the sensor is on I2C or SPI, since a bus transfer takes time.
sensor_channel_get(dev, channel, &value) then reads the stored result. It does no bus traffic and has no side effects on the driver’s state. A channel names a kind of measurement: SENSOR_CHAN_AMBIENT_TEMP is ambient temperature in degrees Celsius, SENSOR_CHAN_PRESS is pressure in kilopascal, SENSOR_CHAN_HUMIDITY is humidity in percent. One fetch can fill several channels. The BME280 fills all three from a single bus read.
Why two calls? One bus transfer gets all channels at once, and the split lets you pay for it once. It also separates when the world is sampled from when you look. You can fetch in a timed task and read the numbers elsewhere.
Small microcontrollers often have no hardware floating point, and floats print badly. Zephyr’s answer is the struct sensor_value, with two fields. val1 is the integer part. val2 is the fractional part in one-millionths. The value is val1 + val2 × 10−6.
The docs give two examples. 0.5 is val1 = 0, val2 = 500000. −1.5 is val1 = −1, val2 = −500000. Notice the second: both fields carry the sign. A reading of −0.5 is val1 = 0, val2 = −500000, and a printf of val1 alone would show 0, with the minus lost. Helpers such as sensor_value_to_double and sensor_value_to_milli exist for the conversion.
The BME280 itself reports temperature in steps of 0.01 °C. So a reading of 23.45 °C comes back as val1 = 23, val2 = 450000. The last four digits of val2 are always zero for this chip, because its resolution is coarser than the format allows.
Move the real temperature. The app still sees the old stored value. Press Fetch to read the chip, then Get to read the stored value into a sensor_value.
A virtual BME280. The burst read of 8 bytes from register 0xF7 (pressure, temperature, humidity) and the 0.01 °C step follow the Bosch datasheet; the temperature path is modelled and the pressure and humidity bytes are not shown. The val1 and val2 rule is from the Zephyr header.
val1 = 23, val2 = 450000. No bus traffic.sensor_channel_get has no side effects. It cannot know the world moved.val1 = −1, val2 = −500000.The symptom of the stale read is a reading that never changes, while the chip is fine. The measurement is a logic analyzer on SDA and SCL: if there is no transaction between your get calls, the data cannot be new. The fix is to put the fetch before the get, once per sample.
The docs describe a second API that is newer but, in their words, rapidly stabilizing: read and decode. The Zephyr docs say it is expected that fetch and get will be deprecated in favour of it, in the near future. It is built on RTIO, a queue of I/O requests that the hardware can work through without blocking your thread.
The sample shows the shape. sensor_read(&iodev, &ctx, buf, 128) asks for a set of channels (the iodev lists them once, at build time) and fills a raw buffer. sensor_get_decoder(dev, &decoder) returns a decoder. decoder->decode(...) turns the raw buffer into a data struct for a channel. The decoder must be made of pure stateless functions, so any state lives in the buffer. That makes it safe to ship the buffer elsewhere, perhaps to another core, and decode it there.
The API changes the cost model. The driver’s submit call must not block. It starts the transfer, returns, and the result arrives later. The same app can now sample several sensors at once without parking a thread on each bus.
On real hardware. On an nRF52840 DK with a BME280, call fetch and get once per second in a loop. Probe SDA and SCL. You should see one transaction per fetch: a write of the register address 0xF7, then a read of 8 bytes. Warm the chip with your finger and watch val1 climb.
sensor_value holds val1 = −1 and val2 = −500000. What temperature is it, in °C?Chapter 9
Weigh what the framework saves against what it costs, and decide with a measurement instead of a taste
Two engineers argue in a design review. One says: “It is a sensor loop and an LED. Zephyr is a sledgehammer.” The other says: “We will have three boards and a radio by spring. Bare metal is a trap.” Both are right about different products.
This chapter gives you the reasons to put on a table, so the argument ends in a number.
Look back at Chapter 0. The framework turns most hardware change into config edits. That pays off most when the hardware varies: several boards, several vendors, or a board that will have revisions.
It also gives you parts that are costly to write alone. The kernel brings threads, queues and timers (see RTOS under the hood). The tree brings drivers, a logging system and a sensor API. The Nordic Developer Academy teaches the nRF Connect SDK, which is built on Zephyr, so the Bluetooth LE stack and the update tooling of that SDK arrive through the same build you have just learned. A team that needs a radio stack and a bootloader inherits both.
It brings a shared vocabulary. A new engineer who knows prj.conf, overlays and west can read any Zephyr project. In bare metal every code base has its own startup file, its own driver style and its own build.
First, learning. You have just spent nine chapters on the tools and have not yet written a threaded app. Second, code size. The kernel and drivers are real code in flash and RAM. How much depends on your config, so the honest number comes from your build. Every west build ends with a memory report that lists each region, its used bytes, its size and the percent used. Read that table before you decide.
Third, indirection. When an LED does not blink you now have more places to look: the overlay, the merged tree, the .config, the init order. Chapters 2 to 6 gave you the places to look. The cost is real, and you pay it every time something is wrong.
Fourth, timing. A kernel has scheduling, and interrupts can be delayed by kernel work. For a loop with a hard cycle-exact budget, such as a motor current loop that must run on a PWM timer edge, the usual answer is to keep that loop in a tight interrupt handler in both approaches. The framework does not change that code. It is still a register-level handler.
Linux also uses a devicetree, and the ideas match: nodes, compatible strings, bindings. The difference is when it is read. A Linux kernel receives the tree as a binary blob at boot and parses it at run time, so one kernel image can serve many boards. In Zephyr the build reads the tree on your computer and bakes the answers into C. There is no parser on the chip, and no tree at run time. That is why Zephyr fits small parts. It is also why changing a devicetree means a rebuild. A planned lesson on the Linux device tree and device model covers the kernel side; embedded Linux introduces it now.
Read each situation. Choose the approach you would defend in a design review. You will see the reason either way.
Judgement calls, not laws. The reasons rest on the costs above. Run the memory report on your own build before you rely on any of them.
The failure mode is deciding by taste and finding out late. The symptom: a project six months in that cannot fit the radio stack, or one that spends a week porting a driver between boards. The measurement is the memory report from step 2, taken in week one. The fix is to take the measurement first.
On real hardware. Build the blinky sample in Zephyr for an STM32 Nucleo and write the same blink in register code. Compare the memory report with the size of your bare-metal binary, and the line count of each. Both numbers are yours to measure; this lesson does not guess them.
Chapter 10
Keep the numbers, the checklist and the smallest working app, and follow the links to the next lessons
Zephyr turns a project into three kinds of file and one tool. West fetches the source at pinned revisions. Devicetree says what hardware exists and how it starts. Kconfig says which software to build, under rules. Your C reads both through generated names. Drivers start before main, in an order set by priority, and your app talks to them through shared APIs for logging and sensing.
| What | Number or term | Why it matters |
|---|---|---|
| Blinky period | SLEEP_TIME_MS = 1000 (toggle every 1,000 ms) | A 2,000 ms square wave on the pin |
| led0 on the nRF52840 DK | gpio0 pin 13, active low (led1 is pin 14) | Logical on means 0 V |
| led0 on Nucleo F446RE and L476RG | gpioa pin 5, active high | Same C code drives 3.3 V |
| uart0 on the nRF52840 DK | uart@40002000, current-speed 115200 | A hardware setting lives in devicetree |
| I2C0 default pins on the DK | SDA P0.26, SCL P0.27 | Edit both default and sleep states to move them |
| Overlay search order | socs/ then boards/BOARD.overlay, then BOARD.overlay, then app.overlay | Overlays are joined after the board file |
| Kconfig merge order | board defconfig, CONFIG_ cache entries, then prj.conf | Your prj.conf beats the board default |
| Generated files | zephyr.dts, devicetree_generated.h, .config, autoconf.h | Open them before you guess |
| Log levels | ERR 1, WRN 2, INF 3, DBG 4 (0 is none) | Levels above the module level cost nothing |
| One 62-byte line at 115,200 baud, 8N1 | 5.38 ms; at most 185 lines per second | Why immediate logging can starve a loop |
| Init priority | 0 to 999, lower first; SENSOR_INIT_PRIORITY default 90 | The bus must start before the sensor |
| sensor_value | val1 integer part, val2 in millionths; −1.5 is (−1, −500000) | Both fields carry the sign |
| BME280 read | 8 bytes from 0xF7; 0.01 °C step | One fetch fills temperature, pressure and humidity |
west list between machines.prj.conf.CONFIG_ line, read build/zephyr/.config. Set KCONFIG_WARNING_AS_ERROR=y.build/zephyr/zephyr.dts when a node or alias seems wrong.default and the sleep state.device_is_ready before the first use of any device.Three files make a temperature logger for an nRF52840 DK with a BME280 on I2C0. The overlay turns on the bus and adds the sensor node. The prj.conf asks for the subsystems. The C is the fetch-and-get loop with logging.
boards/nrf52840dk_nrf52840.overlay&i2c0 { status = "okay"; clock-frequency = <I2C_BITRATE_STANDARD>; bme280@76 { compatible = "bosch,bme280"; /* picks the driver (Ch 6); enables DT_HAS_... (Ch 2) */ reg = <0x76>; /* I2C address, SDO low */ }; }; prj.confCONFIG_SENSOR=y # the guard BME280 sits under (Ch 5) CONFIG_LOG=y # logging on, deferred by default (Ch 7) src/main.c#include <zephyr/kernel.h> #include <zephyr/device.h> #include <zephyr/drivers/sensor.h> #include <zephyr/logging/log.h> LOG_MODULE_REGISTER(app, LOG_LEVEL_INF); /* Ch 7 */ int main(void) { const struct device *dev = DEVICE_DT_GET_ANY(bosch_bme280); /* NULL if no enabled node (Ch 6) */ struct sensor_value t; if (dev == NULL || !device_is_ready(dev)) { LOG_ERR("no ready BME280"); return 0; } while (1) { if (sensor_sample_fetch(dev) == 0 && /* one I2C burst read (Ch 8) */ sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &t) == 0) { LOG_INF("temperature %d milli-degrees C", (int)sensor_value_to_milli(&t)); } k_sleep(K_SECONDS(1)); } }
Build it with west build -b nrf52840dk/nrf52840 app and flash with west flash. The board target form needs Zephyr 3.7 or later.
Zephyr is one of several routes. FreeRTOS gives you a kernel and leaves drivers, build and hardware description to you or to a vendor HAL. Vendor SDKs often wrap one of these. The nRF Connect SDK from Nordic is built on Zephyr, which is why the Nordic Academy teaches these tools. Embedded Rust (its own lesson) and Linux take different paths to the same questions: who describes the hardware, and when.
This lesson was built from primary sources, opened for this page: the Zephyr documentation (devicetree, Kconfig, west, logging, sensor, pin control, device model) and the Zephyr source tree for the board files, the BME280 driver and binding, and the blinky and BME280 samples. The teaching order follows the Nordic Developer Academy’s nRF Connect SDK Fundamentals, the Memfault Interrupt series Practical Zephyr, and the Golioth Zephyr training. The BME280 register and resolution facts come from the Bosch datasheet. All devices here are models, not builds, and say so.
Now press Present or Teach and explain from memory how one alias line in an overlay changes which pin blinks, why a CONFIG_ line can be ignored, and what happens to a sensor that starts before its bus. Then go back to the LED at the top, delete the alias on a Nucleo board, and say aloud which file the build error points at and which file you would fix.