Introduction
The goal of this book is to provide a detailed getting-started guide for using the Rust programming language with ESP32-C3 devices from Espressif.
This book will guide users through the process of creating a no_std Rust application using esp-hal, demonstrating the use of various hardware peripherals as we progress. More information regarding the application we will be building can be found in the Project Overview chapter.
We assume some familiarity with Rust; see the Prerequisites chapter for more details.
You can join the esp-rs community on Matrix for any technical questions or issues you may have. The community is open to everybody.
How to Use This Book
This book assumes that you’re reading it front-to-back. Later chapters build on concepts introduced in earlier chapters, and earlier chapters may omit details which are covered in more depth later on in the book.
Source code for the application we will be building can be found in the esp-rs/no_std-training repository.
Conventions Used in This Book
We use icons to mark different kinds of information in the book:
- ✅ Call for action.
- ⚠️ Warnings, details that require special attention.
- 🔎 Knowledge that dives deeper into a subject but which you are not required to understand before proceeding.
- 💡 Hints that might help you during the exercises.
Example note: Notes like this one contain helpful information
In some Rust files, you may find some anchor comments:
// ANCHOR: test
let foo = 1;
...
// ANCHOR_END: test
Anchor comments can be ignored, they are only used to introduce those parts of code in this book. See the mdBook documentation.
Re-using This Material
This book is distributed under the following licenses:
- The code contained within this book is licensed under the terms of both the MIT License and the Apache License v2.0.
- The written prose, pictures and diagrams contained within this book are licensed under the terms of the Creative Commons CC-BY-SA v4.0 license.
If you want to use our text or images in your work, you must:
- Give the appropriate credit (i.e. mention this book on your slide, and provide a link to the relevant page).
- Provide a link to the CC-BY-SA v4.0 license.
- Indicate if you have changed the material in any way, and make any changes to our material available under the same license.
Prerequisites
This chapter contains information on the knowledge, hardware, and software required in order to complete this training.
Rust
Some level of prior experience with Rust, and programming in general, is expected. This training does not aim to teach programming or Rust in general, as many high-quality resources are already available for these topics.
If you are completely new to the language, we recommend you first read The Rust Book. You may also wish to first read The Rust on ESP Book, though this is not required reading.
Toolchain
The latest stable Rust toolchain is required, and you will need to install the riscv32imc-unknown-none-elf target.
Rust should be installed using the official installer, found at https://rustup.rs/. The required toolchain and target can be installed by running:
rustup toolchain install stable --target riscv32imc-unknown-none-elf
Additional Software
We will also use espflash for loading the firmware to the device. This can be installed using Cargo:
cargo install espflash --locked
Hardware
We will use the ESP32-C3-DevKit-RUST-2 development kit for this training. While it’s possible to use other development kits, this board contains sensors and other devices which will be used by our application, so it is strongly recommended to use this particular kit for the best results.
The source files for this development kit are available in the esp-rs/esp-rust-board repository. This development kit is available on AliExpress and Mouser, see Where to buy.
Building a Data Logger Application
In the following chapters we will build a simple data logger application from scratch, progressively adding more functionality with each chapter.
Before we start, we will present a high-level overview of the application we will be building in Project Overview.
Project Overview
In this training we will be building a simple data-logger application. The application will connect to a Wi-Fi network, read data from a sensor, and send the data to an MQTT broker.
The intent of this training is to produce an application which resembles a “real-world” project, covering what we consider to be some essential topics, without requiring you to write thousands of lines of code before arriving at a finished product.
- First, in Project Setup, we will guide you through the process of initializing a project. We will generate a new skeleton project and explain its components.
- In Reading Sensor Data, we will start with device initialization, so that our board is properly configured and ready to use moving forward. Next, we read data from a connected temperature/humidity sensor over the I2C bus.
- In Wi-Fi Connectivity, we will cover the basics of connecting to a local Wi-Fi network and establishing a connection to the Internet.
- With a sensor and Wi-Fi initialized, in Publishing Data to an MQTT Broker we will connect to an MQTT broker and send our sensor data to the broker.
- In Wi-Fi Provisioning, we will step back to the topic of Wi-Fi and demonstrate how to set up Wi-Fi provisioning, allowing the device to be connected to arbitrary networks without requiring the network credentials to be hard-coded in the firmware.
- Finally, we will explain how to update devices in the field using Over-the-Air Updates.
Project Setup
Generating a Project
We will begin by generating a bare-bones project as a starting point. We provide a tool, esp-generate, specifically for such cases. It can be installed by running:
cargo install --locked esp-generate
With esp-generate installed, we can now generate an empty project:
esp-generate --headless --chip=esp32c3 -o unstable-hal -o embassy no_std-training
Since we are targeting the ESP32-C3-DevKit-RUST-2 development kit, we select the ESP32-C3 for our chip. We will take advantage of asynchronous support via Embassy, so both the embassy and unstable options are required.
You should now see no_std-training/ in the executing directory.
Project Structure
Your newly generated project should look as follows:
no_std-training/
├─ .cargo/
│ └─ config.toml
├─ .clippy.toml
├─ build.rs
├─ Cargo.toml
├─ rust-toolchain.toml
└─ src/
├─ bin/
│ └─ main.rs
└─ lib.rs
Let’s quickly walk through the purpose of each of these files:
.cargo/config.tomlcontains configuration for Cargo.- The build target is provided, in this case
riscv32imc-unknown-none-elf. - Rust compiler flags are provided to force frame pointers. This is required in order for backtraces to work correctly. This is not required if not using the
esp-backtracecrate. - Additionally, we configure espflash to be used as the Cargo runner for the project.
- The build target is provided, in this case
.clippy.tomlcontains configuration for Clippy, a linter for Rust code.build.rsconfigures the Rust compiler to include the required linker scripts.- This could also be configured in
.cargo/config.toml, but this approach provides better diagnostics in the case of build errors.
- This could also be configured in
Cargo.tomlis the Cargo manifest, which contains project metadata, dependencies, and more.rust-toolchain.tomlspecifies which Rust toolchain to use, in addition to specifying the required components and the build target.src/lib.rscontains any library code for our application. This is currently empty, but will be populated in later chapters.src/bin/main.rsis the entry point of our application. This is where most of our logic will live.
Dependencies
The generated Cargo.toml comes pre-populated with a number of dependencies, whose purposes are briefly described below:
esp-hal- The Hardware Abstraction Layer. Provides access to on-chip peripherals using high-level APIs.esp-rtos- Provides the runtime support necessary to run asynchronous code on top ofesp-hal.esp-bootloader-esp-idf- Support package for using the ESP-IDF bootloader.embassy-executor- Asynchronous executor for embedded devices. Allows us to run one or more asynchronous tasks.embassy-time- Asynchronous timekeeping, delays, and timeouts.critical-section- Critical sections for embedded devices.static_cell- Statically allocated, initialized at runtime cell.
Additional dependencies will be included in later chapters as well.
A Minimal Application
The src/bin/main.rs contains some boilerplate for a minimal application:
#![no_std]
#![no_main]
#![deny(
clippy::mem_forget,
reason = "mem::forget is generally not safe to do with esp_hal types, especially those \
holding buffers for the duration of a data transfer."
)]
#![deny(clippy::large_stack_frames)]
use embassy_executor::Spawner;
use embassy_time::{Duration, Timer};
use esp_hal::clock::CpuClock;
use esp_hal::timer::timg::TimerGroup;
#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
loop {}
}
// This creates a default app-descriptor required by the ESP-IDF bootloader.
// For more information see: <https://docs.espressif.com/projects/esp-idf/en/stable/esp32c3/api-reference/system/app_image_format.html#application-description>
esp_bootloader_esp_idf::esp_app_desc!();
#[allow(
clippy::large_stack_frames,
reason = "it's not unusual to allocate larger buffers etc. in main"
)]
#[esp_rtos::main]
async fn main(spawner: Spawner) -> ! {
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
let peripherals = esp_hal::init(config);
let timg0 = TimerGroup::new(peripherals.TIMG0);
let sw_interrupt =
esp_hal::interrupt::software::SoftwareInterruptControl::new(peripherals.SW_INTERRUPT);
esp_rtos::start(timg0.timer0, sw_interrupt.software_interrupt0);
// TODO: Spawn some tasks
let _ = spawner;
loop {
Timer::after(Duration::from_secs(1)).await;
}
// for inspiration have a look at the examples at https://github.com/esp-rs/esp-hal/tree/main/examples
}
This should mostly be straightforward, however, there are a few interesting parts which we will explain briefly.
Application Description
The ESP-IDF bootloader expects an Application Description structure to be located at a specific address. Failure to include this description will result in confusing bootloader errors.
The Application Description is generated via the following macro invocation:
#![allow(unused)]
fn main() {
esp_bootloader_esp_idf::esp_app_desc!();
}
No further action is required. See the ESP-IDF Documentation for further details.
#[esp_rtos::main] Macro
The #[esp_rtos::main] macro is used to define the application’s entry point, usually the main function:
#[esp_rtos::main]
async fn main(spawner: Spawner) -> ! {
// ...
}
This macro creates a new instance of an Embassy Executor and spawns the main function as an asynchronous task.
Reading Sensor Data
In this chapter we will initialize the board, configure the I2C bus, and read temperature and humidity from the SHTC3 sensor on the ESP32-C3-DevKit-RUST-2. Each successful measurement is printed using the log crate, while sensor errors are reported with error-level log messages.
The completed code for this chapter is available in project/part1/.
Initialization
The beginning of the application prepares logging, configures the chip, and starts the runtime support used by the rest of the application. We will look at each step separately.
Panic Handler
In a no_std application, a panic handler must be provided. The minimal application in the previous chapter used a manual #[panic_handler], but in this chapter we use esp-backtrace instead:
use esp_backtrace as _;
The panic-handler feature of esp-backtrace provides the panic handler for us, and also gives useful backtrace support when something goes wrong.
Logger
First, we initialize the logger:
esp_println::logger::init_logger_from_env();
This lets us use the standard log macros. In this chapter we use info! to print successful temperature and humidity readings, and error! to report failures while starting or reading a measurement.
init_logger_from_env() configures logging from the ESP_LOG environment variable. The value is similar to the RUST_LOG filtering used by env_logger and can be set when building or running the application:
ESP_LOG=info cargo run --release
Common global levels are error, warn, info, debug, trace, and off. For example, use ESP_LOG=warn to show only warnings and errors, or ESP_LOG=debug to include debug messages as well.
You can also set the default log level in .cargo/config.toml:
[env]
ESP_LOG = "info"
With this configuration, cargo run --release will use ESP_LOG=info unless you override it in the shell.
You can also filter individual modules:
ESP_LOG=warn,no_std_training=info cargo run --release
This enables info logs for this application while keeping other modules at warn.
esp_hal::init
esp_hal::Config describes the system configuration that should be applied during HAL initialization. It is a non-exhaustive type, so we create it with Config::default() and then adjust the parts we care about. In this application, we use with_cpu_clock(CpuClock::max()) to request the maximum CPU clock:
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
let peripherals = esp_hal::init(config);
esp_hal::init applies that configuration. It sets up the CPU clock and watchdog, then returns the peripherals and clocks needed by the HAL.
The important value for the next steps is peripherals. It contains one Rust value for each hardware block and pin. When we later create drivers, we pass those values into the driver constructors. That transfer of ownership is how esp-hal prevents accidental double-use of hardware: once peripherals.I2C0 has been moved into the I2C driver below, no other driver can use the same I2C peripheral.
esp_rtos::start
The application uses async Rust through Embassy. esp_rtos::start starts the scheduler used by esp-rtos and Embassy. It needs a hardware timer and a software interrupt:
let timg0 = TimerGroup::new(peripherals.TIMG0);
let sw_interrupt =
esp_hal::interrupt::software::SoftwareInterruptControl::new(peripherals.SW_INTERRUPT);
esp_rtos::start(timg0.timer0, sw_interrupt.software_interrupt0);
The timer is used to drive time-based async operations, such as Timer::after(...). The software interrupt is used by the runtime to wake tasks.
Drivers
Next we create an I2C bus driver for the sensor:
let sda = peripherals.GPIO10;
let scl = peripherals.GPIO8;
let i2c = I2c::new(peripherals.I2C0, Config::default())
.expect("Failed to create I2C bus")
.with_sda(sda)
.with_scl(scl)
.into_async();
let mut sht = shtc3(i2c);
I2c::new takes ownership of the I2C peripheral and a configuration. The ESP32-C3-DevKit-RUST-2 connects the SHTC3 sensor to GPIO10 for SDA and GPIO8 for SCL, so we attach those pins with the with_* methods.
Many esp-hal drivers follow this pattern:
- Create the driver with the hardware peripheral and a configuration.
- Attach pins or optional settings with
with_*methods, such aswith_sdaandwith_scl. - Choose the execution mode.
The final call, into_async, converts the I2C driver into its async mode. This lets the sensor driver use async I2C operations and lets our task await transfers instead of busy-waiting.
This blocking/async split is common across esp-hal drivers. Driver types are parameterized by a mode, and async-capable drivers use the Async mode marker after conversion. The exact setup method varies by peripheral, but the pattern is the same: create the driver, configure it, then convert it to async mode when it will be used from async code.
Finally, shtc3(i2c) wraps the I2C bus in the sensor-specific driver from the shtcx2 crate.
Reading the Sensor
The SHTC3 is a temperature and humidity sensor controlled over I2C. The SHTC3 datasheet describes the command set, measurement modes, timing requirements, and conversion formulas. We do not need to implement those details manually; the shtcx2 crate sends the commands and converts the raw values for us.
The application still needs to follow the sensor’s measurement sequence. A reading is not returned by a single I2C transaction; instead, we:
- Ask the sensor to start a measurement.
- Wait until the measurement is complete.
- Read and convert the result.
In code this looks like:
// Read sensor
if let Err(e) = sht.start_measurement(PowerMode::NormalMode).await {
error!("Failed to start measurement: {:?}", e);
Timer::after(Duration::from_secs(1)).await;
continue;
}
// Wait for the maximum measurement duration reported by the sensor driver.
let duration = max_measurement_duration(&sht, PowerMode::NormalMode);
Timer::after(Duration::from_micros(duration.into())).await;
let measurement = match sht.get_measurement_result().await {
Ok(m) => m,
Err(e) => {
error!("Failed to get measurement result: {:?}", e);
Timer::after(Duration::from_secs(1)).await;
continue;
}
};
We use PowerMode::NormalMode, which is the higher-precision measurement mode. After start_measurement(...), the SHTC3 is busy converting the temperature and humidity internally. If we try to read immediately, the sensor may not acknowledge the I2C read yet.
There are a few ways a sensor can tell us that a measurement is ready. Some sensors expose a data-ready interrupt pin; the SHTC3 used on this board is a 4-pin I2C device (VDD, SCL, SDA, and VSS), so there is no interrupt pin for this example to await. The SHTC3 also supports clock stretching, but the measurement commands used by this driver do not enable it. We therefore wait for the maximum measurement duration reported by max_measurement_duration(...) before trying to read the result.
This wait is separate from the async I2C transfers. Async I2C lets the task yield while I2C commands are sent or received; Timer::after(...).await lets the task yield while the sensor performs the measurement. In both cases, the executor can run other work instead of busy-waiting.
The returned measurement exposes typed temperature and humidity values:
info!(
" {:.2} °C | {:.2} %RH",
measurement.temperature.as_degrees_celsius(),
measurement.humidity.as_percent(),
);
The loop repeats this sequence once per second, logging the latest reading.
Running the Application
Flash and run the application from project/part1/:
cargo run --release
This command does two things. First, Cargo builds the application in release mode for the configured ESP32-C3 target. Then Cargo runs the target-specific runner from .cargo/config.toml:
[target.riscv32imc-unknown-none-elf]
runner = "espflash flash --monitor --chip esp32c3"
The runner invokes espflash to flash the binary to the board. The --monitor flag keeps the serial monitor open after flashing, so the log output from the device is printed in the same terminal.
Once the application starts, it initializes the board, configures the async I2C driver, and repeatedly reads the SHTC3 sensor. Each loop prints the latest temperature and relative humidity measurement.
You should see output similar to:
INFO - 24.31 °C | 42.18 %RH
INFO - 24.30 °C | 42.21 %RH
INFO - 24.32 °C | 42.20 %RH
At this point the application can initialize the board, configure an async I2C driver, and read sensor data. In the next chapter we will connect the device to Wi-Fi so that these measurements can be sent off the board.
Wi-Fi Connectivity
In this chapter we connect the board to a local Wi-Fi network, obtain an IP address, and send each sensor reading to a computer on the same network. The completed code for this chapter is available in project/part2/.
The HAL initialization, I2C setup, and SHTC3 measurement sequence from Reading Sensor Data stay the same. What changes is the structure of the project and the new networking pieces: a heap, a network stack, background tasks, and compile-time credentials.
From One File to Modules
The previous chapter kept everything in main.rs. Once we add Wi-Fi and HTTP, that file would become hard to follow, so we move related code into modules:
mod http;
mod network;
mod sensor;
sensor.rsholds the SHTC3 measurement helper that used to live in the main loop. The I2C bus is still created inmain, but starting a measurement, waiting for it, and converting the result now live inread_sensor:
pub async fn read_sensor(sht: &mut ShtC3<I2c<'static, esp_hal::Async>>) -> Option<(f32, f32)> {
// Read sensor
if let Err(e) = sht.start_measurement(PowerMode::NormalMode).await {
error!("Failed to start measurement: {:?}", e);
return None;
}
// Wait for the maximum measurement duration reported by the sensor driver.
let duration = max_measurement_duration(sht, PowerMode::NormalMode);
Timer::after(Duration::from_micros(duration.into())).await;
match sht.get_measurement_result().await {
Ok(m) => {
let temp = m.temperature.as_degrees_celsius();
let humidity = m.humidity.as_percent();
info!(" {:.2} °C | {:.2} %RH", temp, humidity);
Some((temp, humidity))
}
Err(e) => {
error!("Failed to get measurement result: {:?}", e);
None
}
}
}
network.rsowns the two background tasks that keep the radio associated and the IP stack running.http.rsbuilds a JSON payload and sends it with a minimal HTTPPOST.main.rsstill initializes the hardware, starts the network stack, and runs the application loop.
This split keeps the new networking concepts easier to read, and the same modules will grow in later chapters.
Why We Need esp-alloc
A no_std program has no global allocator unless we provide one. The previous chapter never needed a heap: the sensor driver works with stack buffers, and we never built a String or a Vec.
Wi-Fi is different. esp-radio wraps the precompiled radio driver, and that driver allocates at runtime. embassy-net and our HTTP helper also need the alloc crate, for example when format! builds the JSON body. Without a heap, the application would not even start the radio.
We therefore add esp-alloc and enable the alloc crate:
extern crate alloc;
use esp_alloc as _;
extern crate alloc; makes Vec, String, and format! available in no_std. use esp_alloc as _; pulls in the crate so its global allocator is linked, even though we do not call it by name.
Then we create the heap before starting the scheduler or the radio:
esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024);
esp_alloc::heap_allocator!(size: 36 * 1024);
heap_allocator! can be invoked more than once. Each invocation adds a region to the same global allocator. For the ESP32-C3 used in this training, the calls reserve two heap regions:
- 64 KiB of reclaimed memory, selected by
#[ram(reclaimed)]. - Another 36 KiB of memory.
See Allocating Memory in The Rust on ESP Book for more details.
esp-radiorequires both a heap and a running scheduler. We still callesp_rtos::start(...)beforeesp_radio::wifi::new(...), just as the crate documentation requires.
Initializing the Network Stack
Networking is split into two layers. esp-radio drives the Wi-Fi hardware. embassy-net is the IP stack that sits on top of that interface and gives us DHCP, DNS, and TCP.
Creating the Wi-Fi Interface
After the scheduler is running, we take ownership of the Wi-Fi peripheral and create a station-mode interface:
let (controller, interfaces) = esp_radio::wifi::new(peripherals.WIFI, Default::default())
.expect("Failed to create WiFi controller");
let wifi_interface = interfaces.station;
esp_radio::wifi::new returns a WifiController and a set of interfaces. The controller associates with an access point. interfaces.station is the embassy-net driver: a Wi-Fi client that can send and receive Ethernet frames.
embassy-net Configuration
embassy-net is configured in two places: Cargo features, and the Config value we pass at runtime.
The crate features select which protocols are compiled in:
embassy-net = { version = "0.9.1", features = [
"dhcpv4",
"dns",
"medium-ethernet",
"tcp",
"udp",
] }
medium-ethernetis required because a Wi-Fi station presents an Ethernet-like interface.dhcpv4lets the stack request an IPv4 address from the access point.udpis used by DHCP and DNS.tcpanddnsare used later when we open a socket and resolve a host.
We also enable Embassy support in esp-rtos, and the wifi feature on esp-radio:
esp-radio = { version = "0.18.0", features = [
"esp32c3",
"log-04",
"unstable",
"wifi",
] }
esp-rtos = { version = "0.3.0", features = [
"embassy",
"esp-radio",
"esp32c3",
"log-04",
] }
At runtime we ask for a DHCP lease and seed the stack from the hardware RNG:
let config = embassy_net::Config::dhcpv4(Default::default());
let rng = Rng::new();
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
Config::dhcpv4 is the embassy-net equivalent of “get an address from the router”. A static address would also work, but DHCP is the usual setup on a development network and avoids hard-coding an IP in firmware.
The random seed is not a cryptographic key. embassy-net uses it for protocol values that must not be predictable across devices, such as TCP initial sequence numbers and DHCP transaction IDs.
Why the Stack Resources Are Static
embassy_net::new needs a Wi-Fi driver, the config, a random seed, and a StackResources<N> buffer. N is the number of sockets the stack can keep open at once. We use 3, which is enough for DHCP, DNS, and one TCP connection.
// Init network stack
static STACK_RESOURCES_CELL: static_cell::StaticCell<StackResources<3>> =
static_cell::StaticCell::new();
let (stack, runner) = embassy_net::new(
wifi_interface,
config,
STACK_RESOURCES_CELL
.uninit()
.write(StackResources::<3>::new()),
seed,
);
Those resources, the Runner, and the spawned tasks all need a 'static lifetime. Embassy tasks are not allowed to borrow data from main’s stack: once spawned, a task can run for the rest of the program, so every argument must outlive main.
A plain local let resources = StackResources::new(); would be dropped when main returned (it never does, but the type system cannot use that fact) and could not be given to a 'static task. A static mut would compile only with unsafe.
StaticCell solves this. It is a one-time cell: we initialize it at runtime, then get a &'static mut StackResources<3>. After that, embassy_net::new returns a Stack we can use from application code and a Runner that must be polled continuously.
Why We Use Tasks
The stack is not useful until two loops run in the background:
spawner.spawn(connection(controller).expect("failed to spawn connection task"));
spawner.spawn(net_task(runner).expect("failed to spawn network task"));
Both functions are Embassy tasks, created with #[embassy_executor::task].
connection owns the WifiController. It configures station mode, connects, and if the link drops it waits and tries again:
#[embassy_executor::task]
pub async fn connection(mut controller: WifiController<'static>) {
debug!("start connection task");
loop {
if controller.is_connected() {
let _ = controller.wait_for_disconnect_async().await;
Timer::after(Duration::from_millis(5000)).await;
continue;
}
let station_config = WifiConfig::Station(
StationConfig::default()
.with_ssid(SSID)
.with_password(PASSWORD.into()),
);
controller
.set_config(&station_config)
.expect("Failed to set WiFi configuration");
debug!("About to connect...");
match controller.connect_async().await {
Ok(_) => info!("Wifi connected!"),
Err(e) => {
error!("Failed to connect to wifi: {e:?}");
Timer::after(Duration::from_millis(5000)).await
}
}
}
}
net_task owns the Runner. Its only job is to keep polling the IP stack:
#[embassy_executor::task]
pub async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
runner.run().await
}
We use tasks because these two loops never finish, and they must make progress at the same time as the application. If main called runner.run().await itself, it would never read the sensor or send HTTP. If it only ran the connection loop, DHCP and TCP would stall. Embassy’s executor interleaves the tasks whenever one of them .awaits, so the radio, the IP stack, and the application loop can all run on a single core.
The 'static lifetimes on WifiController and Runner are the same constraint as before: a spawned task may outlive the function that spawned it.
Environment Variables
The network name and password are not written as string literals. They are read at compile time:
const SSID: &str = env!("SSID");
const PASSWORD: &str = env!("PASSWORD");
env! expands to a &'static str taken from the environment when rustc runs. If SSID or PASSWORD is missing, the build fails. That keeps credentials out of the source tree, and it means you pass them when you build or flash:
SSID="your-ssid" PASSWORD="your-password" cargo run --release
Cargo forwards process environment variables to the compiler, so these values are baked into the firmware. Changing the network later requires rebuilding.
The HTTP helper uses optional variables for the receiver on your computer:
const HOST_IP: Option<&'static str> = option_env!("HOST_IP");
const HTTP_PORT: Option<&'static str> = option_env!("HTTP_PORT");
const DEFAULT_HTTP_PORT: u16 = 8080;
option_env! yields None when the variable is unset, so the firmware still builds. At runtime, send_sensor_data logs an error and returns if HOST_IP is missing. HTTP_PORT defaults to 8080.
Waiting for an Address, Then Sending Data
After the tasks are spawned, main waits until the link is up and DHCP has assigned an address:
stack.wait_link_up().await;
debug!("Waiting to get IP address...");
loop {
if let Some(config) = stack.config_v4() {
debug!("Got IP: {}", config.address);
break;
}
embassy_time::Timer::after(Duration::from_millis(500)).await;
}
wait_link_up() completes when the station is associated. The following loop waits until config_v4() is Some, which means the DHCP lease is in place. Only then do we start sending.
The application loop is now two calls: read the sensor, and if that succeeds, post the values:
// Read sensor
if let Some((temp, humidity)) = read_sensor(&mut sht).await {
// Send sensor data via HTTP
let _ = send_sensor_data(stack, temp, humidity).await;
}
send_sensor_data formats a small JSON body, opens a TCP socket, and writes a hand-built HTTP/1.0 POST to /sensor:
// Prepare HTTP payload (JSON)
let temperature_str = format!("{:.2}", temperature);
let humidity_str = format!("{:.2}", humidity);
let body = format!(
r#"{{"temperature":{},"humidity":{}}}"#,
temperature_str, humidity_str
);
This chapter uses HTTP only as a simple way to prove that the device can reach another host. The next chapter replaces this with MQTT.
Running the Application
The firmware posts to a computer on the same network. From the repository root, start the receiver first:
cargo xtask http-server
The task prints a host IP when it can detect one. Use that value as HOST_IP. Then, from project/part2/, flash the application:
SSID="your-ssid" PASSWORD="your-password" HOST_IP="192.168.1.10" cargo run --release
Replace the SSID, password, and IP with your network and the address printed by xtask. You can also set HTTP_PORT if the server is not on 8080.
Once the device associates, you should see a connection log on the serial monitor:
INFO - Wifi connected!
INFO - 24.31 °C | 42.18 %RH
INFO - HTTP request sent
The http-server terminal should print each payload:
sensor payload={"temperature":24.31,"humidity":42.18}
At this point the board can join a Wi-Fi network, obtain an IP address, and send measurements off-device. In the next chapter we will publish those readings to an MQTT broker.
Publishing Data to an MQTT Broker
In this chapter we replace the temporary HTTP request from the previous chapter with MQTT. The board connects to an MQTT broker, reads the SHTC3 sensor, and publishes the temperature once per second. The completed code for this chapter is available in project/part3/.
The I2C, Wi-Fi, and network-stack initialization from Wi-Fi Connectivity stay the same. The main changes are the MQTT client, a dedicated task that owns the sensor, and a local broker that lets us inspect each publication.
Wi-Fi Credentials
This chapter continues to use the compile-time SSID and PASSWORD introduced in the previous chapter. Keeping the Wi-Fi setup unchanged lets us focus on MQTT. In the next chapter, we will replace these compile-time credentials with a Wi-Fi provisioning portal.
What MQTT Adds
MQTT is a publish/subscribe protocol. Instead of sending an HTTP request directly to a particular application endpoint, a client publishes a payload to a named topic on a broker. Other clients can subscribe to that topic and receive the payload.
This chapter uses three MQTT concepts:
- The broker accepts connections and routes messages.
- The ESP32-C3 is a publisher.
measurement/temperatureis the topic to which the device publishes.
The local broker started later in this chapter also subscribes to measurement/#. The # wildcard matches every topic below measurement, so the broker’s logger prints messages sent to measurement/temperature.
Adding the MQTT Client
The MQTT implementation lives in a new module:
mod mqtt;
We use the rust-mqtt crate:
rust-mqtt = { version = "0.5.1", default-features = false, features = ["bump", "v5"] }
Default features are disabled because this is a no_std application. The v5 feature selects MQTT version 5, which matches the local broker, and bump enables the crate’s bump-buffer storage. A bump buffer reserves a fixed block of memory up front and lets the client use it for MQTT packets without requiring a separate heap allocation for each operation.
Starting the MQTT Task
In the previous chapter, main owned the sensor and performed every read and HTTP request. We now move that loop into an Embassy task:
spawner.spawn(mqtt_task(stack, sht).expect("failed to spawn MQTT task"));
Stack is a lightweight, copyable handle to the network stack, so it can be passed to the task while net_task continues to drive the stack’s runner. The SHTC3 driver is moved into mqtt_task, giving that task exclusive ownership of the I2C sensor.
After spawning the background tasks, main has no more application work to perform. It remains alive and yields to the executor:
// Keep main task alive
loop {
embassy_time::Timer::after(embassy_time::Duration::from_secs(60)).await;
}
The network connection task, network runner, and MQTT task can now make progress independently whenever the other tasks are waiting.
Initializing MQTT
The MQTT task first reserves receive and transmit buffers for its TCP socket:
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
These buffers live for the entire task and are reused for every connection attempt.
Waiting for the Network
MQTT runs over TCP, so the task cannot connect to the broker until Wi-Fi is associated and DHCP has configured the network stack:
// Wait for network to be ready before attempting connection
debug!("Waiting for WiFi link to come up...");
stack.wait_link_up().await;
debug!("WiFi link up, waiting for network configuration...");
// Wait for DHCP to assign an IP address
stack.wait_config_up().await;
debug!("Waiting to get IP address...");
loop {
if let Some(config) = stack.config_v4() {
debug!("Got IP: {}", config.address);
break;
}
Timer::after(Duration::from_millis(500)).await;
}
// Check if we still have a valid network config before proceeding
if !stack.is_config_up() {
debug!("Network config lost, retrying...");
continue;
}
wait_link_up() waits for the Wi-Fi link. wait_config_up() waits for the network configuration, and config_v4() confirms that an IPv4 address is available. If the configuration disappears before the broker connection starts, the outer loop begins the sequence again.
Locating the Broker
The broker address and port are read at compile time:
let host = match HOST_IP {
Some(h) => h,
None => {
error!(
"No HOST_IP set. Provide e.g. HOST_IP=10.0.0.10 (or hostname) and optional BROKER_PORT."
);
Timer::after(Duration::from_secs(5)).await;
continue;
}
};
// Default to rumqttd's v5 listener port (1884) unless overridden
let port: u16 = BROKER_PORT
.and_then(|p| p.parse::<u16>().ok())
.unwrap_or(1884);
Both values are baked into the firmware when it is compiled. HOST_IP is required by the application logic, but it uses option_env! so a missing value produces a log error rather than a compiler error. BROKER_PORT is optional and defaults to 1884, the port used by this training’s local MQTT broker.
Despite its name, HOST_IP can also contain a hostname. The task first tries to parse the value as an IPv4 address. If parsing fails, it asks the network stack to resolve an IPv4 address with DNS:
// If host is an IPv4 literal, bypass DNS
let address = match host.parse::<Ipv4Address>() {
Ok(ipv4) => IpAddress::Ipv4(ipv4),
Err(_) => match stack.dns_query(host, DnsQueryType::A).await {
Ok(addresses) if !addresses.is_empty() => addresses[0],
Ok(_) => {
error!("DNS query returned no addresses for {}", host);
Timer::after(Duration::from_secs(5)).await;
continue;
}
Err(e) => {
error!("DNS lookup error: {e:?}");
Timer::after(Duration::from_secs(5)).await;
continue;
}
},
};
Using a literal IP address avoids the DNS lookup. This is useful for the local broker, whose address is normally the IP address of the computer running the training.
Opening TCP and Connecting MQTT
Next, the task opens a TCP socket to the resolved broker address:
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
socket.set_timeout(Some(embassy_time::Duration::from_secs(10)));
let remote_endpoint = (address, port);
info!("connecting to MQTT broker at {}:{}...", host, port);
let connection = socket.connect(remote_endpoint).await;
if let Err(e) = connection {
error!("connect error: {:?}", e);
Timer::after(Duration::from_secs(5)).await;
continue;
}
info!("connected!");
The ten-second timeout prevents a connection attempt from waiting forever. A failed TCP connection pauses for five seconds and then returns to the beginning of the outer loop.
Once TCP is connected, we can initialize the MQTT client:
let mut mqtt_buffer_storage = [0; 1024];
let mut mqtt_buffer = BumpBuffer::new(&mut mqtt_buffer_storage);
let mut client = Client::<_, _, 1, 1, 1, 1>::new(&mut mqtt_buffer);
// rumqttd rejects the default keep alive of 0, which disables keep alive
let connect_options = ConnectOptions::new()
.clean_start()
.keep_alive(KeepAlive::Seconds(
NonZero::new(60).expect("non-zero keep alive"),
));
let client_id = MqttString::from_str("esp32c3").expect("valid MQTT client id");
if let Err(e) = client
.connect(socket, &connect_options, Some(client_id))
.await
{
error!("MQTT connect error: {:?}", e);
continue;
}
The 1 KiB BumpBuffer supplies working storage for MQTT packets. clean_start() asks the broker to begin without a previous MQTT session, and esp32c3 identifies this client to the broker.
keep_alive(...) promises the broker that the client sends a packet at least every 60 seconds. If the broker hears nothing for one and a half times that interval, it considers the client gone and closes the connection. Our publications every second keep the connection alive. The default, KeepAlive::Infinite, sends 0 and disables the mechanism, but the local broker rejects connections without a keep alive. client.connect(...) sends the MQTT CONNECT packet over the TCP socket and waits for the broker to accept it.
TCP and MQTT are separate connection layers. A successful socket.connect(...) only establishes a byte stream to the broker. A successful client.connect(...) completes the MQTT handshake over that stream.
Finally, the task creates the topic and publication options once per MQTT connection:
let topic = TopicName::new(
MqttString::from_str("measurement/temperature").expect("valid MQTT topic string"),
)
.expect("valid MQTT topic name");
let publish_options = PublicationOptions::new(TopicReference::Name(topic)).retain();
The topic is measurement/temperature. Calling retain() asks the broker to keep the latest value, so a new subscriber can receive the most recent temperature without waiting for the next sensor reading.
Publishing Measurements
The inner loop is the steady-state part of the task. Before reading the sensor, it verifies that both the Wi-Fi link and network configuration are still available:
// Check network state before attempting operations
if !stack.is_link_up() || !stack.is_config_up() {
debug!("Network connection lost, reconnecting...");
break;
}
If either has been lost, break leaves the publication loop. The outer loop then waits for the network and creates fresh TCP and MQTT connections.
For each publication, the task reads the sensor and formats the temperature:
// Read sensor
let (temp, _) = match read_sensor(&mut sht).await {
Some(reading) => reading,
None => {
Timer::after(Duration::from_secs(1)).await;
continue;
}
};
let mut temperature_string: heapless::String<32> = heapless::String::new();
write!(temperature_string, "{:.2}", temp).expect("write! failed!");
read_sensor still returns both temperature and humidity, but this chapter publishes only temperature. The _ pattern intentionally discards the humidity value. A fixed-capacity heapless::String holds the formatted number, avoiding a heap allocation for every reading.
The string’s bytes become the MQTT payload:
if let Err(e) = client
.publish(&publish_options, Bytes::from(temperature_string.as_bytes()))
.await
{
error!("MQTT publish error: {:?}", e);
break;
}
If publication succeeds, the task waits one second and reads again. If it fails, the task leaves the inner loop and reconnects. This gives the application one recovery path for a lost Wi-Fi link, a lost IP configuration, a closed TCP socket, or an MQTT error.
Running the Application
Start the MQTT broker from the repository root:
cargo xtask mqtt-server
The command starts an MQTT version 5 broker on port 1884, subscribes its logger to measurement/#, and prints the computer’s IP address when it can detect one:
MQTT server listening on 0.0.0.0:1884
Host IP (best effort): 192.168.1.10
Remote devices should connect to 192.168.1.10:1884
Subscribed to `measurement/#` and printing all incoming MQTT messages.
Keep that command running. In another terminal, change to project/part3/ and flash the application:
SSID="your-ssid" PASSWORD="your-password" HOST_IP="your-ip" cargo run --release
Replace your-ip with the host IP printed by the previous command, and replace the credentials with values for your network. The board and the computer running the broker must be reachable from one another. To use a different broker port, pass the same port to both commands:
cargo xtask mqtt-server --port 1885
SSID="your-ssid" PASSWORD="your-password" HOST_IP="your-ip" BROKER_PORT="1885" cargo run --release
After Wi-Fi, TCP, and MQTT connect, the serial monitor should show sensor readings:
INFO - Wifi connected!
INFO - connecting to MQTT broker at 192.168.1.10:1884...
INFO - connected!
INFO - 24.31 °C | 42.18 %RH
The broker terminal should print each retained publication:
Topic: measurement/temperature | Payload: 24.31
At this point the board can maintain an MQTT connection and publish sensor measurements to a broker. In the next chapter we will replace the compile-time Wi-Fi credentials with a provisioning portal.
Wi-Fi Provisioning
In this chapter we remove the compile-time Wi-Fi credentials. Instead, the board starts its own access point and serves a small web page where you enter the network name and password. Once the credentials arrive, the board leaves access point mode, joins the network, and publishes sensor data to the MQTT broker as before. The completed code for this chapter is available in project/part4/.
The I2C setup, the heap, and the MQTT task from Publishing Data to an MQTT Broker stay mostly the same. The MQTT task now also publishes humidity to measurement/humidity. The main changes are a second network stack, a set of small servers that run on the device, and a channel that hands the credentials from the web page to the Wi-Fi connection task.
What Is Wi-Fi Provisioning?
So far, SSID and PASSWORD were read with env! and baked into the firmware. That works on a development desk, but it does not scale to real devices:
- Every network requires a different firmware image.
- The person installing the device usually cannot rebuild and flash firmware.
- Changing the router or the password means reflashing the device.
Wi-Fi provisioning is the process of delivering network credentials to an unconfigured device at runtime. The firmware is the same for every unit, and the user supplies the credentials during setup.
There are several ways to get credentials onto a device, but the two most common are:
- Access point (SoftAP): the device creates its own Wi-Fi network. The user connects to it with a phone or laptop and enters the credentials, either in a web page served by the device or in a companion app.
- Bluetooth Low Energy (BLE): the device advertises over BLE, and a phone app sends the credentials over a BLE connection. The device’s Wi-Fi radio never has to act as an access point, and the phone stays connected to its own network during setup.
ESP-IDF supports both transports in its unified provisioning framework, and Espressif provides companion apps for Android and iOS.
In this chapter we use the access point approach with a web page. It needs nothing on the user’s side except a browser, and it only uses the Wi-Fi stack we already have.
The provisioning flow looks like this:
sequenceDiagram
participant User as Phone or laptop
participant AP as ESP32-C3 (access point)
participant Router as Wi-Fi router
participant Broker as MQTT broker
AP->>AP: Start access point "esp-radio"
User->>AP: Join "esp-radio"
AP-->>User: DHCP lease (192.168.2.x)
User->>AP: GET http://192.168.2.1/
AP-->>User: Provisioning page
User->>AP: POST /save (SSID and password)
AP-->>User: "Configuration Saved!"
AP->>AP: Switch to station mode
AP->>Router: Join network with received credentials
Router-->>AP: DHCP lease
AP->>Broker: Connect and publish measurements
Station and Access Point Modes
The Wi-Fi radio can play two roles:
- In station (STA) mode, the device is a client that joins an existing network. This is what we used in the previous chapters.
- In access point (AP) mode, the device is the network. Other devices find its SSID, join it, and talk to it directly.
Provisioning needs both: AP mode to receive the credentials, then STA mode to use them.
Two Interfaces, Two Network Stacks
esp_radio::wifi::new already returned more than the station interface. In this chapter we use both the access point and the station Interfaces:
let (controller, interfaces) = esp_radio::wifi::new(peripherals.WIFI, Default::default())
.expect("Failed to create WiFi controller");
// Start with AP device for provisioning
let ap_device = interfaces.access_point;
// Store STA device for later use
let sta_device = interfaces.station;
Each interface is a separate network device, so each one gets its own embassy-net stack:
let NetworkStacks {
ap_stack,
ap_runner,
sta_stack,
sta_runner,
} = create_network_stacks(ap_device, sta_device, gw_ip_addr);
The two stacks are configured differently:
let ap_config = embassy_net::Config::ipv4_static(StaticConfigV4 {
address: Ipv4Cidr::new(gw_ip_addr, 24),
gateway: Some(gw_ip_addr),
dns_servers: Default::default(),
});
let sta_config = embassy_net::Config::dhcpv4(Default::default());
- The station stack uses DHCP, exactly as before, because the router assigns its address.
- The access point stack uses a static address. There is no router on the device’s own network, so nobody else can hand it an address. The device is the gateway of a
/24subnet and uses the gateway address for itself.
The gateway address defaults to 192.168.2.1 and can be overridden at compile time with GATEWAY_IP:
let gw_ip_addr_str = GW_IP_ADDR_ENV.unwrap_or("192.168.2.1");
let gw_ip_addr = Ipv4Addr::from_str(gw_ip_addr_str).expect("failed to parse gateway ip");
The access point stack also needs more sockets than the station stack, because it hosts servers for DHCP, DNS, and HTTP:
// Init network stack for AP (provisioning)
// Increased from 3 to 6 to accommodate: DHCP UDP socket, Captive Portal UDP socket,
// HTTP TCP socket, and some buffer for concurrent connections
static AP_STACK_RESOURCES_CELL: static_cell::StaticCell<StackResources<6>> =
static_cell::StaticCell::new();
let (ap_stack, ap_runner) = embassy_net::new(
ap_device,
ap_config,
AP_STACK_RESOURCES_CELL
.uninit()
.write(StackResources::<6>::new()),
seed,
);
The station stack keeps the StackResources<3> from the previous chapters. Both stacks still need StaticCell, for the same 'static lifetime reasons described in Wi-Fi Connectivity.
Configuring the Controller
The interfaces only carry frames. The WifiController decides which role the radio plays, and the connection task starts it in access point mode:
// Start in AP mode first for provisioning. `set_config` starts/restarts the
// Wi-Fi controller as needed in esp-radio 0.18.
let ap_config = WifiConfig::AccessPoint(AccessPointConfig::default().with_ssid("esp-radio"));
controller
.set_config(&ap_config)
.expect("Failed to set WiFi configuration");
info!("WiFi AP started!");
AccessPointConfig defaults to an open network on channel 1. We only change the SSID to esp-radio, which is the network you will join from your phone or computer.
After the credentials arrive, the same task replaces the configuration with a StationConfig:
// Configure station mode. This replaces the AP configuration and restarts Wi-Fi.
debug!("Configuring station mode...");
let station_config = StationConfig::default()
.with_ssid(credentials.ssid.as_str())
.with_password(credentials.password.as_str().into());
let sta_config = WifiConfig::Station(station_config);
controller
.set_config(&sta_config)
.expect("Failed to set station mode WiFi configuration");
debug!("WiFi station configured!");
set_config restarts Wi-Fi in the new mode, so the access point disappears and the provisioning page is no longer reachable. The station then connects and reconnects with the same loop used in the previous chapters.
esp-radioalso supports running both roles at once withConfig::AccessPointStation. This would let the portal stay up while the device tries the new credentials, for example to report a wrong password back to the user. We keep the two phases separate to keep the example small.
Tasks and Why We Need Them
The application now has seven concurrent activities. main initializes the hardware, creates the shared resources, and spawns most of the tasks:
spawner.spawn(
connection(controller, wifi_credentials_channel).expect("failed to spawn connection task"),
);
spawner.spawn(net_task(ap_runner).expect("failed to spawn AP network task"));
spawner.spawn(sta_net_task(sta_runner).expect("failed to spawn STA network task"));
spawner.spawn(run_dhcp(ap_stack, gw_ip_addr).expect("failed to spawn DHCP task"));
spawner.spawn(
run_captive_portal(ap_stack, gw_ip_addr).expect("failed to spawn captive portal task"),
);
spawner.spawn(mqtt_task(sta_stack, sht).expect("failed to spawn MQTT task"));
| Task | Stack | Responsibility |
|---|---|---|
connection | — | Owns the WifiController, starts the access point, then switches to station mode. |
net_task | AP | Polls the access point stack’s Runner. |
sta_net_task | STA | Polls the station stack’s Runner. |
run_dhcp | AP | Hands out IP addresses to clients that join the access point. |
run_captive_portal | AP | Answers DNS queries with the device’s own address. |
run_http_server | AP | Serves the provisioning page and receives the credentials. |
mqtt_task | STA | Reads the sensor and publishes measurements, as in the previous chapter. |
Each of these is a loop that never finishes. Most of them spend their time waiting for a packet, a connection, or a message. Because they are separate Embassy tasks, the executor runs whichever one has work to do, and the waiting ones cost nothing. A single sequential main could not wait for an HTTP request, answer DHCP, and poll two network stacks at the same time.
Two Runner Tasks
Every embassy-net stack needs its Runner to be polled continuously, so we need one runner task per stack:
#[embassy_executor::task]
pub async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
runner.run().await
}
#[embassy_executor::task]
pub async fn sta_net_task(mut runner: Runner<'static, Interface<'static>>) {
runner.run().await
}
The two functions are identical. They exist separately because a function marked with #[embassy_executor::task] has a fixed-size, statically allocated task pool, and its default size is one. Spawning net_task a second time would fail. An alternative is #[embassy_executor::task(pool_size = 2)], but two named tasks make it clearer which runner belongs to which stack.
Servers on the Access Point
A phone that joins esp-radio expects the same services a normal router provides. The provisioning tasks provide the minimum set, using crates from the edge-net family that run on top of embassy-net through edge-nal-embassy.
These crates are new dependencies in Cargo.toml:
edge-captive = { version = "0.8.0", default-features = false, features = [
"io",
] }
edge-dhcp = "0.8.0"
edge-http = { version = "0.8.0", default-features = false, features = [
"edge-nal",
"embedded-io-async",
"io",
] }
edge-nal = "0.7.0"
edge-nal-embassy = "0.9.0"
run_dhcp uses edge-dhcp to assign addresses to clients. Without it, the user would have to configure a static IP address by hand before reaching the page:
loop {
_ = io::server::run(
&mut Server::<_, 64>::new_with_et(gw_ip_addr),
&ServerOptions::new(gw_ip_addr, Some(&mut gw_buf)),
&mut bound_socket,
&mut buf,
)
.await
.inspect_err(|e| log::warn!("DHCP server error: {e:?}"));
Timer::after(EmbassyDuration::from_millis(500)).await;
}
run_captive_portal uses edge-captive, a DNS server that answers every query with the gateway address. Its purpose is to make every hostname lead to the provisioning page:
loop {
debug!("Starting Captive Portal DNS server");
_ = run(
&udp_stack,
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, DNS_PORT)),
&mut tx_buf,
&mut rx_buf,
gw_ip_addr,
Duration::from_secs(60),
)
.await
.inspect_err(|e| log::warn!("Captive Portal DNS server error: {e:?}"));
Timer::after(EmbassyDuration::from_millis(500)).await;
}
run_http_server uses edge-http to serve the provisioning page on port 80:
static TCP_BUFFERS: static_cell::StaticCell<TcpBuffers<1, 2048, 2048>> =
static_cell::StaticCell::new();
let buffers = TCP_BUFFERS.uninit().write(TcpBuffers::new());
let tcp = Tcp::new(stack, buffers);
let mut acceptor = tcp
.bind(SocketAddr::new(
core::net::IpAddr::V4(core::net::Ipv4Addr::UNSPECIFIED),
HTTP_PORT,
))
.await
.expect("Failed to bind TCP socket");
let handler = HttpHandler {
wifi_credentials_channel,
};
let mut server = HttpServer::<1, 2048, 32>::new();
loop {
if let Err(_e) = server
.run(Some(50000), &mut acceptor, &handler)
.await
.inspect_err(|e| error!("HTTP server error: {:?}", e))
{
Timer::after(EmbassyDuration::from_millis(100)).await;
}
}
main spawns the HTTP server only after the access point stack is up and configured, and then logs the instructions for joining the portal:
ap_stack.wait_link_up().await;
info!("WiFi Provisioning Portal Ready");
info!("1. Connect to the AP: `esp-radio`");
info!("2. Navigate to: http://{gw_ip_addr_str}/");
ap_stack.wait_config_up().await;
ap_stack
.config_v4()
.inspect(|c| debug!("ipv4 config: {c:?}"));
spawner.spawn(
run_http_server(ap_stack, wifi_credentials_channel)
.expect("failed to spawn HTTP server task"),
);
The mqtt_task is spawned immediately, but it does nothing useful yet. Its first step is stack.wait_link_up() on the station stack, so it waits until provisioning is complete and the station has joined the network.
Captive Portals
When a phone or laptop joins a new network, the operating system requests a well-known URL, such as /generate_204 on Android or /connecttest.txt on Windows, to check for Internet access. Public hotspots use this check to open a sign-in page automatically. This is called a captive portal.
The HTTP handler redirects those probe URLs to the provisioning page:
// Handle captive portal redirects
const CAPTIVE_PATHS: &[&str] =
&["/generate_204", "/gen_204", "/ncsi.txt", "/connecttest.txt"];
if CAPTIVE_PATHS.contains(&path) {
conn.initiate_response(302, Some("Found"), &[("Location", "/")])
.await?;
return Ok(());
}
For the operating system to send its probe to the device, the client must use the device as its DNS server. In this project, the DNS responder listens on UDP port 8853, while clients send DNS queries to the standard port 53, and the DHCP server does not advertise a DNS server. As a result, the portal page does not open automatically: you open it yourself at http://192.168.2.1/.
Passing Credentials Between Tasks
The HTTP server receives the credentials, but the connection task owns the WifiController. The two tasks communicate through an embassy-sync Channel:
// Create WiFi credentials channel
static WIFI_CREDENTIALS_CHANNEL_CELL: static_cell::StaticCell<
Channel<embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex, WifiCredentials, 1>,
> = static_cell::StaticCell::new();
let wifi_credentials_channel = WIFI_CREDENTIALS_CHANNEL_CELL.uninit().write(Channel::new());
The channel has a capacity of one message, because we only need a single set of credentials. It uses a CriticalSectionRawMutex, which is safe to share between tasks and interrupts. Like the stack resources, it lives in a StaticCell so both tasks can hold a &'static reference.
The message type is a small struct:
#[derive(Clone, Debug, Deserialize)]
pub struct WifiCredentials {
pub ssid: String<32>,
pub password: String<64>,
}
The fields are fixed-capacity heapless::Strings sized to the Wi-Fi limits: an SSID is at most 32 bytes, and a WPA2 passphrase is at most 63 characters, or 64 hexadecimal digits. Deriving Deserialize lets the HTTP handler build the struct directly from the JSON request body. The serde feature on heapless makes this possible.
The connection task waits on the receiving end:
// Wait for credentials
debug!("Waiting for WiFi credentials...");
let credentials = wifi_credentials_channel.receiver().receive().await;
info!("Credentials received! SSID: {}", credentials.ssid);
// Give the HTTP handler time to send the saved page before switching off AP mode.
debug!("Delaying AP shutdown to allow HTTP response to complete...");
Timer::after(EmbassyDuration::from_secs(2)).await;
receive().await suspends the task until a message arrives, without polling. The two-second delay gives the HTTP server time to finish sending the confirmation page before the access point shuts down.
Serving the Provisioning Page
The HTTP handler matches on the request method and path. A GET / returns the provisioning page:
(Method::Get, "/") => {
conn.initiate_response(
200,
Some("OK"),
&[("Content-Type", "text/html; charset=utf-8")],
)
.await?;
conn.write_all(HOME_HTML.as_bytes()).await?;
}
GET /saved returns the confirmation page in the same way. Any other path returns 404 Not Found.
The form submits the credentials as JSON to POST /save:
(Method::Post, "/save") => {
// Read request body
let mut buf = [0u8; 256];
let n = match conn.read(&mut buf).await {
Ok(0) => {
conn.initiate_response(400, Some("Bad Request"), &[])
.await?;
return Ok(());
}
Ok(n) => n,
Err(e) => return Err(e),
};
match serde_json_core::from_slice::<WifiCredentials>(&buf[..n])
.ok()
.map(|(credentials, _)| credentials)
{
Some(credentials) => {
debug!(
"WiFi Credentials Received: SSID: {} | Password: {}",
credentials.ssid, credentials.password
);
self.wifi_credentials_channel
.sender()
.send(credentials)
.await;
debug!("Credentials sent!");
conn.initiate_response(
200,
Some("OK"),
&[("Content-Type", "text/html; charset=utf-8")],
)
.await?;
conn.write_all(SAVED_HTML.as_bytes()).await?;
}
None => {
conn.initiate_response(400, Some("Bad Request"), &[])
.await?;
}
}
}
The handler reads the body into a 256-byte buffer and parses it with serde-json-core, a no_std JSON parser that does not allocate. If parsing succeeds, the credentials are sent through the channel and the handler replies with the confirmation page. If the body is empty or not valid JSON, the handler replies with 400 Bad Request.
The handler logs the received password at the
debuglevel. That is useful while learning, but a real product should never log secrets.
HTML Templates
The two pages live in project/part4/assets/templates/:
home.htmlis the provisioning form with SSID and password fields.saved.htmlis the confirmation page shown after the credentials are submitted.
There is no file system on the device. Instead, include_str! embeds both files in the firmware at compile time:
// HTML templates embedded at compile time
const HOME_HTML: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/assets/templates/home.html"
));
const SAVED_HTML: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/assets/templates/saved.html"
));
CARGO_MANIFEST_DIR is the directory that contains Cargo.toml, so the paths do not depend on the directory from which you run Cargo. The pages become &'static str constants stored in flash, and the handler writes their bytes directly to the TCP connection.
Keep a few things in mind when editing them:
- Despite the directory name, the pages are not processed by a template engine. They are served exactly as written.
- Changes require a rebuild and reflash, because the HTML is part of the firmware image.
home.htmldisplaysesp-radioand192.168.2.1as plain text. If you change the access point SSID orGATEWAY_IP, update the page as well.- The form uses a small JavaScript
fetchcall to send JSON rather than the browser’s default form encoding. This is what lets the firmware parse the body withserde-json-coreintoWifiCredentials. On success, the script navigates to/saved. - Every byte of HTML and CSS increases the size of the firmware. Inline styles and no external resources keep the pages self-contained, which matters because the client has no Internet access while connected to the access point.
Running the Application
Start the MQTT broker from the repository root:
cargo xtask mqtt-server
In another terminal, change to project/part4/ and flash the application. SSID and PASSWORD are no longer needed:
HOST_IP="your-ip" cargo run --release
Replace your-ip with the host IP printed by cargo xtask mqtt-server. BROKER_PORT works as in the previous chapter, and GATEWAY_IP changes the address of the provisioning portal.
After boot, the serial monitor shows the portal instructions:
INFO - WiFi AP started!
INFO - Starting Captive Portal DNS server on port 8853
INFO - WiFi Provisioning Portal Ready
INFO - 1. Connect to the AP: `esp-radio`
INFO - 2. Navigate to: http://192.168.2.1/
INFO - Starting HTTP server on port 80
Then provision the device:
- On a phone or computer, join the open Wi-Fi network
esp-radio. - Open
http://192.168.2.1/in a browser. Usehttp://, nothttps://. - Enter the SSID and password of the network on which the MQTT broker is reachable, then select Save Configuration.
- Reconnect your phone or computer to its usual network. The
esp-radionetwork disappears once the device switches to station mode.
The serial monitor shows the switch to station mode, followed by the MQTT connection and the sensor readings:
INFO - Credentials received! SSID: your-ssid
INFO - Connecting to WiFi network...
INFO - Successfully connected to WiFi!
INFO - connecting to MQTT broker at 192.168.1.10:1884...
INFO - connected!
INFO - 24.31 °C | 42.18 %RH
The broker terminal now prints both topics:
Topic: measurement/temperature | Payload: 24.31
Topic: measurement/humidity | Payload: 42.18
If the password is wrong, the connection task keeps retrying every five seconds. Reset the board to start the provisioning portal again.
Limitations
This example shows the core of Wi-Fi provisioning, but it leaves out several things a product would need:
- The credentials are not persisted. They only live in RAM, so every reset starts the provisioning portal again. A real device would store them in flash and only start the portal when no valid credentials are stored.
- The access point is open. Anyone nearby can join it and submit credentials, and the password travels in plain HTTP. Protecting the access point with a WPA2 password, or using a provisioning protocol with its own encryption, such as the security schemes in ESP-IDF’s provisioning component, would address this.
- There is no feedback on failure. The access point is gone by the time the device tries the credentials, so the user cannot see a connection failure on the page.
At this point the device no longer needs credentials at compile time: the same firmware can join any network. In the next chapter we will look at updating that firmware in the field with Over-the-Air Updates.
Over-the-Air Updates
In this chapter we teach the device to update its own firmware. The board periodically asks a server on your computer for a new application image, writes the image to a spare region of flash, and reboots into it. The completed code for this chapter is available in project/part5/.
Wi-Fi provisioning and the MQTT task from Wi-Fi Provisioning stay the same. The main changes are a custom partition table, flash access from the application, a task that downloads and installs new firmware, and a status LED that shows what the device is doing.
What Is an OTA Update?
Until now, every new version of the firmware reached the board through the USB cable and espflash. Once a device is installed in the field, that cable is gone. An Over-the-Air (OTA) update delivers the new firmware through the network connection the device already has.
The difficult part is not the download, but replacing the program that is currently running. The application cannot overwrite itself while it executes, and a power loss in the middle of the update must not leave the device without working firmware.
ESP-IDF solves this with an A/B scheme:
- The flash holds more than one application slot. The application runs from one slot and writes the new image to another.
- A small data partition,
otadata, records which slot should boot next. - Only after the new image is completely written does the application update
otadataand reboot. - The second-stage bootloader reads
otadataand starts the selected slot.
If the download fails halfway, otadata still points to the old slot and nothing is lost. Our application uses the same ESP-IDF bootloader as before, so it follows these rules too.
The full update flow looks like this:
sequenceDiagram
participant Host as Computer (OTA server)
participant App as ESP32-C3 application
participant Flash as Flash memory
participant Boot as Bootloader
App->>Host: GET /firmware.bin
Host-->>App: Application image
App->>Flash: Write image to the inactive slot
App->>Flash: Select the new slot in otadata
App->>App: Software reset
Boot->>Flash: Read otadata
Boot->>Flash: Verify and load the new slot
Boot->>App: Start the updated application
Creating the Partition Table
The ESP32-C3 flash is divided into regions. The second-stage bootloader is at the start of the flash, and the partition table at offset 0x8000 describes everything after it: where each partition starts, how large it is, and what it contains. The format is described in the ESP-IDF Partition Tables guide.
In the previous chapters we never provided a partition table, so espflash used its default one. It contains a single application partition, factory, and no room for a second image. For OTA we write our own table in project/part5/partitions.csv:
# ESP-IDF Partition Table
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x4000,
otadata, data, ota, 0xd000, 0x2000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 0x100000,
ota_0, app, ota_0, 0x110000, 0x100000,
ota_1, app, ota_1, 0x210000, 0x100000,
Each row describes one partition:
- Name is a label used to find the partition, for example in tools and logs.
- Type is
appfor partitions that contain firmware anddatafor everything else. - SubType refines the type. It tells the bootloader which partition is the factory image, which ones are OTA slots, and where the OTA data lives.
- Offset and Size place the partition in flash.
- Flags can mark a partition as encrypted or read-only. We do not use them.
The partitions in our table are:
| Partition | Purpose |
|---|---|
nvs | Non-volatile storage, a key-value store for data such as settings. Unused in this training. |
otadata | Records which OTA slot to boot. It holds two copies of the boot selection, so an interrupted write never corrupts both. |
phy_init | Radio calibration data used by the Wi-Fi driver. |
factory | The application flashed with espflash. The bootloader starts it when otadata is empty. |
ota_0 | First OTA slot. |
ota_1 | Second OTA slot. |
A few rules shape the layout:
- The partition table itself occupies offset
0x8000, so the first partition starts at0x9000. - Application partitions must start at an offset aligned to 64 KiB (
0x10000). This is whyfactorystarts at0x10000and each slot starts exactly 1 MiB after the previous one. otadatamust be0x2000bytes, enough for the two copies of the boot selection.- Every application image must fit in its slot. With three 1 MiB application partitions, the table uses a little more than 3 MiB of the 4 MiB flash on the ESP32-C3-DevKit-RUST-2.
The factory partition is not strictly required for OTA, because the bootloader can start from ota_0 directly. Keeping it means that the image flashed over USB stays untouched, and updates alternate between ota_0 and ota_1.
You can ask espflash to parse the CSV file and print the resulting table, which is a quick way to catch typos and overlapping partitions:
espflash partition-table partitions.csv
Flashing With the Partition Table
To use our table, the Cargo runner passes it to espflash:
[target.riscv32imc-unknown-none-elf]
runner = "espflash flash --monitor --chip esp32c3 --partition-table partitions.csv"
espflash now writes the bootloader, our partition table, and the application. It always places the application in the factory partition.
espflash does not erase otadata by default. After the device has installed an OTA update, otadata points to an OTA slot, and the bootloader keeps starting that slot even if you flash a new image to factory with cargo run. To boot the freshly flashed image, erase otadata while flashing:
cargo run --release -- --erase-data-parts ota
Arguments after -- are passed to the runner, so espflash receives --erase-data-parts ota and erases every data partition with the ota subtype.
Accessing the Flash
The application needs to read the partition table and write to the OTA slots. Two crates provide this:
esp-bootloader-esp-idf = { version = "0.5.0", features = ["esp32c3"] }
esp-storage = { version = "0.9.0", features = ["esp32c3"] }
esp-storageprovidesFlashStorage, a driver for the SPI flash chip that implements theembedded-storagetraits.esp-bootloader-esp-idfhas been part of the project from the start, becauseesp_app_desc!()creates the application descriptor that the ESP-IDF bootloader expects. It also understands the partition table andotadata.
At startup, main creates the flash driver, reads the partition table, and logs which partition is running:
let mut flash = esp_storage::FlashStorage::new(peripherals.FLASH);
let mut buffer = [0u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN];
let pt = esp_bootloader_esp_idf::partitions::read_partition_table(&mut flash, &mut buffer)
.expect("Failed to read partition table");
info!("Currently booted partition {:?}", pt.booted_partition());
// Store flash storage in mutex for OTA updates
*FLASH_STORAGE.lock().await = Some(flash);
read_partition_table parses the table into the buffer, and booted_partition reports the partition the running code was loaded from. This log line is how we will tell whether the device is running from factory, ota_0, or ota_1.
The flash driver is created once in main, but the OTA task uses it much later. We move it into a static:
pub static FLASH_STORAGE: Mutex<
embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex,
Option<FlashStorage<'static>>,
> = Mutex::new(None);
The embassy-sync Mutex guarantees that only one task accesses the flash at a time. The value is wrapped in an Option because a static must be initialized at compile time, while FlashStorage can only be created at runtime from the FLASH peripheral. main stores Some(flash) after initialization, and the OTA task locks the mutex when it needs to write.
Creating the Application Image
cargo build produces an ELF file in target/riscv32imc-unknown-none-elf/release/no_std-training. An ELF file contains everything a debugger needs, such as symbols and debug information, but the ESP32-C3 cannot boot it directly. Until now, espflash flash converted the ELF file into an application image on the fly and wrote it to the factory partition.
For an OTA update, we need that application image as a file, so that a server can send it to the device. espflash save-image performs the same conversion and saves the result. Run it from project/part5/ after a release build:
mkdir -p ota
espflash save-image --chip esp32c3 --partition-table partitions.csv target/riscv32imc-unknown-none-elf/release/no_std-training ota/firmware.bin
save-image does not create missing directories, so mkdir -p ota comes first. The repository’s .gitignore already excludes ota/ directories, so the generated image is never committed.
The resulting firmware.bin is exactly what belongs in an application partition, in the ESP-IDF application image format:
- An image header that starts with the magic byte
0xE9and describes the chip and flash settings. - The application segments: code and data, each with the address it must be loaded to.
- The application descriptor created by
esp_app_desc!(), with the crate version and project name fromCargo.toml, and the build date and time. It sits at the start of the first segment, at a fixed offset, so the device can read the version of an image from its first bytes. - A checksum and a SHA-256 digest that the bootloader verifies before it starts the image.
The image does not contain the bootloader or the partition table. Those are already on the device and do not change during an OTA update. Do not use the --merge option here: it produces a full flash image, with the bootloader and partition table, which only makes sense when writing the flash from offset 0.
Passing --partition-table also makes espflash check the image against the size of our application partitions instead of its default factory partition:
App/part. size: 718,080/1,048,576 bytes, 68.48%
The exact size depends on your build. If the image ever grows past 1 MiB, it no longer fits in an OTA slot, and you need to change the partition table on every device, which an OTA update cannot do.
Serving the Image Over HTTP
The device downloads the image with a plain HTTP GET request. The repository’s xtask includes a small server for this. Run it from the repository root, pointing it to the image created above:
cargo xtask ota-server --firmware project/part5/ota/firmware.bin
The server reads the file into memory and answers GET /firmware.bin on port 8080. Every response contains the whole image, with a Content-Length header and Connection: close. Any other path returns 404 Not Found. Like the MQTT broker, it prints the host IP address the device should use:
OTA server listening on 0.0.0.0:8080
Host IP (best effort): 192.168.1.10
Example: `HOST_IP="192.168.1.10" cargo r -r`
Remote devices should connect to 192.168.1.10:8080
Serving `GET /firmware.bin` from `project/part5/ota/firmware.bin` (718080 bytes).
The server reads the file only at startup. After you create a new image, restart the server so it serves the new file.
--port changes the port, but the firmware always connects to port 8080, so changing it also requires changing the firmware. The file name in --firmware can be anything, because the URL is always /firmware.bin.
To check the server without a device, download the image with curl and compare it with the original:
curl -o /tmp/firmware.bin http://127.0.0.1:8080/firmware.bin
cmp /tmp/firmware.bin project/part5/ota/firmware.bin
The OTA Client Task
On the device, the OTA logic lives in project/part5/src/ota.rs. main spawns its task, http_client_task, together with the status LED task described later:
spawner.spawn(http_client_task(sta_stack).expect("failed to spawn OTA HTTP client task"));
spawner.spawn(
status_led_task(peripherals.RMT, peripherals.GPIO2).expect("failed to spawn LED task"),
);
The task receives the station stack, because the OTA server is reachable through the network the device joins after provisioning. Its first step is stack.wait_config_up(), so like mqtt_task, it waits until provisioning is complete and DHCP has configured the station.
Checking Periodically
The device does not know when a new image is available, so it asks at a fixed interval. The interval is read at compile time:
fn ota_check_interval() -> EmbassyDuration {
const DEFAULT_SECS: u64 = 300;
let secs = OTA_CHECK_INTERVAL_SECS
.and_then(|raw| raw.parse::<u64>().ok())
.filter(|secs: &u64| *secs > 0)
.unwrap_or(DEFAULT_SECS);
EmbassyDuration::from_secs(secs)
}
The default is 300 seconds. Set OTA_CHECK_INTERVAL_SECS when building to check more often, which is convenient while testing. Values that are missing, zero, or not a number fall back to the default.
The OTA server address comes from the same HOST_IP variable as the MQTT broker, since both servers run on your computer. Unlike the MQTT task, the OTA task does not resolve hostnames: HOST_IP must be an IPv4 address. If it is missing or not an address, the task skips the check and tries again after the interval.
Requesting the Image
Each check is handled by update_firmware. It uses the client side of edge-http, the crate that served the provisioning page in the previous chapter, on top of an edge-nal-embassy TCP connection to port 8080 of the host:
let buffers = TcpBuffers::<1, 1024, 4096>::new();
let tcp = WithTimeout::new(30_000, Tcp::new(stack, &buffers));
let mut http_buffer = [0u8; 1024];
let mut conn: Connection<'_, _> = Connection::new(
&mut http_buffer,
&tcp,
SocketAddr::new(host_ip.into(), OTA_PORT),
);
debug!("HTTP Client: Requesting firmware from {host_ip}:{OTA_PORT}...");
conn.initiate_request(false, Method::Get, "/firmware.bin", &[])
.await
.map_err(|e| error!("HTTP Client: Request error: {e:?}"))?;
conn.initiate_response()
.await
.map_err(|e| error!("HTTP Client: Response error: {e:?}"))?;
TcpBuffers::<1, 1024, 4096>provides the buffers for one TCP socket: 1 KiB to send the request and 4 KiB to receive the image.WithTimeoutgives every network operation a 30-second limit, so a check that stalls, for example because the computer left the network, ends with an error.initiate_requestconnects and sendsGET /firmware.bin. The first argument selectsHTTP/1.0instead ofHTTP/1.1, which asks the server to close the connection after the response.initiate_responsereads the status line and headers intohttp_buffer.
If the server is not running, the connection fails, the task logs the error, and it tries again after the interval:
ERROR - HTTP Client: Request error: Io(Error(Connect(ConnectionReset)))
Checking the Response
A response is not necessarily an image. The server might answer 404 Not Found, or a different program might be listening on port 8080. Before touching the flash, the task checks the headers:
let (headers, body) = conn.split();
if headers.code != 200 {
error!("HTTP Client: Server responded with status {}", headers.code);
return Err(());
}
let Some(content_len) = headers.headers.content_len() else {
error!("HTTP Client: Response has no Content-Length");
return Err(());
};
split separates the parsed headers from the body. Only 200 OK is accepted, and the response must announce its size in Content-Length, so that the task can later tell a complete download from one that was cut short.
Checking the Version
The server offers the same image at every check, so the device must decide whether it needs it. The application descriptor answers this: it stores the crate version from Cargo.toml at a fixed offset near the start of every image. The layout is described by a few constants:
// ESP-IDF application image layout: a 24-byte image header and an 8-byte segment header
// precede the application descriptor created by `esp_app_desc!()`.
const IMAGE_MAGIC: u8 = 0xE9;
const APP_DESC_OFFSET: usize = 32;
const APP_DESC_MAGIC: u32 = 0xABCD_5432;
const VERSION_OFFSET: usize = APP_DESC_OFFSET + 16;
const VERSION_LEN: usize = 32;
const IMAGE_PREFIX_LEN: usize = VERSION_OFFSET + VERSION_LEN;
The task reads the first 80 bytes of the body, which end exactly after the version field, and compares the version with the one of the running firmware:
let mut prefix = [0u8; IMAGE_PREFIX_LEN];
body.read_exact(&mut prefix)
.await
.map_err(|e| error!("HTTP Client: Read error: {e:?}"))?;
let Some(version) = image_version(&prefix) else {
error!("HTTP Client: Response is not an application image");
return Err(());
};
let running_version = crate::ESP_APP_DESC.version();
if version == running_version {
info!("HTTP Client: Firmware {running_version} is up to date");
return Ok(false);
}
info!("HTTP Client: Updating firmware {running_version} -> {version}");
image_version checks both magic numbers before it trusts the bytes in between:
/// Returns the version stored in the application descriptor of an image, or `None` if the
/// bytes do not start an ESP-IDF application image.
fn image_version(prefix: &[u8; IMAGE_PREFIX_LEN]) -> Option<&str> {
let app_desc_magic = prefix[APP_DESC_OFFSET..]
.first_chunk()
.map(|bytes| u32::from_le_bytes(*bytes));
if prefix[0] != IMAGE_MAGIC || app_desc_magic != Some(APP_DESC_MAGIC) {
return None;
}
let version = &prefix[VERSION_OFFSET..];
let len = version.iter().position(|&b| b == 0).unwrap_or(VERSION_LEN);
core::str::from_utf8(&version[..len]).ok()
}
- An image starts with
0xE9, and the application descriptor starts with0xABCD5432. A404page, a text file, or any other data fails these checks, and the task stops withResponse is not an application image. - The version field is 32 bytes long and padded with zero bytes, so the string ends at the first zero.
The running version comes from ESP_APP_DESC, the static created by esp_app_desc!() in main.rs. If both versions are equal, update_firmware returns Ok(false) and closes the connection without downloading the rest. To publish an update, you increase version in Cargo.toml.
The comparison only checks whether the versions differ. A server that offers an older version than the running one would install it as well.
Writing the Image to Flash
Once the image is known to be new, the task locks FLASH_STORAGE and creates an OtaUpdater:
// Initialize OTA updater
let mut ota_buffer = [0u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN];
let mut ota = esp_bootloader_esp_idf::ota_updater::OtaUpdater::new(flash, &mut ota_buffer)
.map_err(|e| {
error!("HTTP Client: Failed to create OTA updater: {:?}", e);
})?;
let (mut next_app_partition, part_type) = ota.next_partition().map_err(|e| {
error!("HTTP Client: Failed to get next partition: {:?}", e);
})?;
debug!("HTTP Client: Flashing image to {:?}", part_type);
OtaUpdater::new reads the partition table again and checks that it contains an otadata partition and at least two OTA slots. With the default espflash partition table, this step fails.
next_partition decides which slot receives the update. It reads otadata to find the currently selected slot and picks the following one: ota_0 after factory, ota_1 after ota_0, and ota_0 again after ota_1. It never returns the slot the application is running from. The returned FlashRegion covers only that partition, with offsets relative to its start, so the task cannot write to the running application, the bootloader, or any other partition by mistake.
The task then writes the image in the order it arrives:
// Write the bytes already read for the version check, then stream the rest
next_app_partition
.write(0, &prefix)
.map_err(|e| error!("HTTP Client: Failed to write chunk at offset 0: {e:?}"))?;
let mut written = IMAGE_PREFIX_LEN;
let mut chunk = [0u8; 4096];
loop {
let n = body
.read(&mut chunk)
.await
.map_err(|e| error!("HTTP Client: Read error: {e:?}"))?;
if n == 0 {
break;
}
next_app_partition
.write(written as u32, &chunk[..n])
.map_err(|e| error!("HTTP Client: Failed to write chunk at offset {written}: {e:?}"))?;
written += n;
}
if written as u64 != content_len {
error!("HTTP Client: Download incomplete ({written} of {content_len} bytes)");
return Err(());
}
debug!("HTTP Client: Firmware download complete ({written} bytes)");
First, the 80 bytes already read for the version check are written at offset 0. Then, each chunk of up to 4 KiB from the body is written right after the previous one. The body reader stops at Content-Length, and a read that returns 0 bytes ends the loop.
A read also returns 0 bytes when the server closes the connection early, so the end of the loop does not prove that the image is complete. The task compares the number of written bytes with Content-Length and refuses a partial image:
ERROR - HTTP Client: Download incomplete (359040 of 718080 bytes)
The image is never held in RAM as a whole. With roughly 700 KB of firmware and about 100 KB of heap, it could not be. Flash can only change bits from 1 to 0, so it must be erased before it is written. The write method of the Storage trait handles this: it erases each 4 KiB sector as needed and preserves the parts of the sector it does not overwrite.
Activating the New Image
After the whole image is in the slot, the task tells the bootloader to use it:
// Activate the next partition
ota.activate_next_partition().map_err(|e| {
error!("HTTP Client: Failed to activate partition: {:?}", e);
})?;
info!("HTTP Client: Partition activated successfully");
// Set OTA state to NEW
match ota.set_current_ota_state(esp_bootloader_esp_idf::ota::OtaImageState::New) {
Ok(()) => {
debug!("HTTP Client: OTA state set to NEW");
}
Err(e) => {
error!("HTTP Client: Failed to set OTA state: {:?}", e);
}
}
activate_next_partitionwrites a new entry tootadatathat selects the slot we just filled. This is the moment the update takes effect: before this call, a reset boots the old firmware, and after it, a reset boots the new one.set_current_ota_statemarks the new slot asOtaImageState::New, a freshly installed image that has not run yet. A bootloader with rollback support uses this state to detect an update that never confirms it works. See Limitations.
Back in the task loop, a reset follows only when update_firmware returns Ok(true), that is, when a new image was installed:
// Attempt firmware update - reset if a new image was installed
LED_STATUS.signal(LedStatus::Updating);
if update_firmware(stack, host_ip).await == Ok(true) {
info!("HTTP Client: Rebooting into updated firmware");
esp_hal::system::software_reset();
}
LED_STATUS.signal(LedStatus::Idle);
Timer::after(ota_interval).await;
software_reset restarts the chip. The bootloader reads otadata, verifies the checksum and SHA-256 digest of the image in the selected slot, and starts it. If the verification fails, the ESP-IDF bootloader falls back to another bootable application partition.
If any step fails before activate_next_partition, the function returns an error, the old firmware keeps running, and the task tries again after the interval. An up-to-date firmware also keeps running and checks again after the interval.
Status LED
The ESP32-C3-DevKit-RUST-2 has an addressable RGB LED connected to GPIO2. status_led_task drives it with the RMT peripheral, which generates the precise pulse timing the LED expects. Other tasks report their state through an embassy-sync Signal, LED_STATUS, and the LED task picks the color:
let color = match status {
LedStatus::Provisioning => (0, 255, 0),
LedStatus::Idle => (0, 0, 0),
LedStatus::Updating => (0, 0, 255),
};
| Color | State | Set by |
|---|---|---|
| Green | Provisioning | main, while the provisioning portal is running. |
| Off | Idle | The OTA task, once the station is connected and between checks. |
| Blue | Updating | The OTA task, while it contacts the server and downloads. |
A Signal only keeps the most recent value, which is exactly what a status indicator needs: the LED task does not care about states it missed, only about the current one.
Running the Application
This walkthrough flashes the application, provisions it, and then updates it with a newer version of itself. Each of the servers runs in its own terminal.
Start the MQTT broker from the repository root:
cargo xtask mqtt-server
In another terminal, change to project/part5/ and flash the application. A short check interval makes the update happen quickly:
HOST_IP="your-ip" OTA_CHECK_INTERVAL_SECS=30 cargo run --release -- --erase-data-parts ota
Replace your-ip with the host IP printed by cargo xtask mqtt-server. Erasing otadata makes sure the device starts from the factory partition, even if an earlier run left an OTA slot selected.
The first log line shows the partition the device booted from:
INFO - Currently booted partition Ok(Some(PartitionEntry { magic: 20650, raw_type: 0, raw_subtype: 0, offset: 65536, len: 1048576, label: "factory", flags: 0, is_read_only: false, is_encrypted: false }))
The provisioning portal instructions from the previous chapter follow, and the LED turns green.
Provision the device as described in Wi-Fi Provisioning. Once the station is connected, the LED turns off, the MQTT task publishes measurements, and the OTA task starts its checks:
INFO - HTTP Client: Periodic OTA checks enabled (every 30s)
No OTA server is running yet, so every check logs a connection error and the old firmware keeps running.
Building the Update
The device only installs an image with a different version, so increase version in project/part5/Cargo.toml:
version = "0.2.0"
Build it with the same environment variables as before. They are baked into the firmware, so an update built without HOST_IP would not find the MQTT broker or the OTA server:
HOST_IP="your-ip" OTA_CHECK_INTERVAL_SECS=30 cargo build --release
mkdir -p ota
espflash save-image --chip esp32c3 --partition-table partitions.csv target/riscv32imc-unknown-none-elf/release/no_std-training ota/firmware.bin
Do not use cargo run here, because it would flash the new firmware over USB.
Applying the Update
In a third terminal, start the OTA server from the repository root:
cargo xtask ota-server --firmware project/part5/ota/firmware.bin
At the next check, the LED turns blue, the server prints Serving firmware.bin with the image size, and the device logs the update:
INFO - HTTP Client: Updating firmware 0.1.0 -> 0.2.0
INFO - HTTP Client: Partition activated successfully
INFO - HTTP Client: OTA update complete
INFO - HTTP Client: Rebooting into updated firmware
The device then resets and boots the new image from ota_0:
INFO - Currently booted partition Ok(Some(PartitionEntry { magic: 20650, raw_type: 0, raw_subtype: 16, offset: 1114112, len: 1048576, label: "ota_0", flags: 0, is_read_only: false, is_encrypted: false }))
The Wi-Fi credentials only lived in RAM, so the updated device starts the provisioning portal again, and the LED turns green. Provision it once more to reconnect it to the network and the MQTT broker.
The OTA server keeps offering the same image, but the device now runs that version, so the following checks leave it alone:
INFO - HTTP Client: Firmware 0.2.0 is up to date
Each of these checks closes the connection after the first bytes of the image, so the server prints failed to write HTTP response body: Broken pipe after Serving firmware.bin. This is expected.
To return to the original firmware, flash it again over USB with --erase-data-parts ota, as in the first step.
Limitations
This example shows the complete OTA mechanism, but a product needs more around it:
- The version check is minimal. The device opens a download at every check just to read the version, and installs any version that differs from its own, including an older one. A real device would ask the server for the latest version first, for example through a small metadata file, and only install newer versions.
- The image is only partly validated before activation. The client checks the status code, the magic numbers, and the length, but not the checksum or the SHA-256 digest. A corrupted image is only rejected by the bootloader at the next boot.
- The download is not authenticated. The image travels over plain HTTP from whichever host answers on
HOST_IP. Anyone who can impersonate that host can install their own firmware. Production devices download over HTTPS and verify signed images, for example with Secure Boot. - There is no rollback. The new image is marked
Newbut never confirms that it works by setting its state toValid. A bootloader built with app rollback support (CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLEin ESP-IDF) boots such an image once, and returns to the previous slot at the next reset if the image has not confirmed itself by then. Using rollback requires that bootloader and a firmware that marks itselfValidonce it has checked that it works, for example after reconnecting to the MQTT broker. - Credentials are lost on every update. As noted in the previous chapter, the Wi-Fi credentials are not stored in flash, so each reboot, including the one after an update, requires provisioning the device again. The
nvspartition in our table is where they could be stored.
With OTA updates in place, a device in the field can receive new firmware without a cable. In Wrapping Up we will review what we built.
Wrapping Up
Congratulations, you have built a complete no_std application for the ESP32-C3. In this chapter we look back at what we built, list what a product would still need, and point to where to go next.
What We Built
Starting from an empty project, we built a data logger that:
- Reads temperature and humidity from the SHTC3 sensor over I2C.
- Starts an access point with a captive portal to receive Wi-Fi credentials at runtime.
- Joins the provisioned network and publishes each measurement to an MQTT broker.
- Periodically checks a server for a new firmware version, installs it in a spare OTA slot, and reboots into it.
- Shows its current state on the RGB LED.
The final application is available in project/part5/.
What We Learned
Along the way we covered:
- How a
no_std,no_mainapplication is structured, and howesp_hal::inithands out peripherals as owned singletons. See Project Setup and Reading Sensor Data. - How to use blocking and async drivers, using I2C and the SHTC3 sensor as an example. See Reading Sensor Data.
- How
esp-rtosruns the Embassy executor, and how to split an application into tasks withstaticresources. See Wi-Fi Connectivity. - When a heap is needed, how to provide one with
esp-alloc, and when fixed-capacityheaplesstypes avoid allocation altogether. See Wi-Fi Connectivity. - How to bring up Wi-Fi with
esp-radioand an IP network withembassy-net. See Wi-Fi Connectivity. - How to publish data with
rust-mqtt. See Publishing Data to an MQTT Broker. - How to run an access point, DHCP, DNS, and HTTP servers on the device with the
edge-*crates, and how to pass data between tasks withembassy-sync. See Wi-Fi Provisioning. - How partition tables,
otadata, and the ESP-IDF bootloader enable safe firmware updates withesp-storageandesp-bootloader-esp-idf. See Over-the-Air Updates.
From Demo to Product
To keep the chapters focused, the application leaves out things a product needs. Each chapter lists its own limitations. Together, they are:
- Persistent configuration. The Wi-Fi credentials only live in RAM, so every reset and every update starts the provisioning portal again. A product stores them in flash and only starts the portal when no valid credentials are stored.
- Security. The provisioning access point is open and the credentials travel over plain HTTP. MQTT and the OTA download are not encrypted, and any host answering on
HOST_IPcan install its own firmware. A product protects the access point, uses TLS, and only boots signed images with Secure Boot. - Update safety. The OTA client installs any version that differs from the running one, and the new image never confirms that it works. A product only installs newer versions and uses app rollback to return to the previous image if the update does not work.
- Robustness. Several initialization steps panic on error, and the tasks retry at fixed intervals. A product handles errors explicitly, uses backoff when it reconnects, and enables a watchdog to recover from a stuck task.
- Power consumption. The radio and CPU stay on all the time. A battery-powered logger would take a measurement, publish it, and spend the rest of the time in deep sleep.
- Observability. Log messages are formatted on the device as text.
defmtmoves formatting to the host, which reduces code size and logging overhead. - Testing. Nothing in the project is tested automatically. Pure logic, such as parsing the image version, can be unit-tested on the host, and code that depends on hardware can run on the device with
embedded-test.
Exercises
If you want to keep going, here are a few ideas that build on the final application:
- ✅ Make the MQTT topic prefix configurable at build time, so that several devices can publish to the same broker.
- ✅ Store the Wi-Fi credentials in flash, so that the device reconnects after a reset or an update without starting the provisioning portal.
- ✅ Subscribe to an MQTT topic, such as
command/interval, and use the received value to change how often the device publishes measurements. - ✅ Use the boot button to clear the stored credentials and start the provisioning portal again.
- ✅ Port the application to another chip, such as the ESP32-C6. You will need to connect an external SHTC3, and change the
esp32c3features and the build target.
Where to Go Next
- The esp-hal documentation describes every driver, and the esp-hal examples show how to use the peripherals we did not cover.
esp-generatecreates new projects with the features you select, as we did in Project Setup.- The esp-rs community on Matrix is the place for questions, and the
esp-rs/no_std-trainingrepository is the place to report issues or suggest improvements to this training.
Bonus Chapters
This section will be filled in the future with chapters on topics that go beyond the data logger application.