Welcome to the Embassy Book. The Embassy Book is for everyone who wants to use Embassy and understand how Embassy works.

Introduction

Embassy is a project to make async/await a first-class option for embedded development.

What is async?

When handling I/O, software must call functions that block program execution until the I/O operation completes. When running inside of an OS such as Linux, such functions generally transfer control to the kernel so that another task (known as a “thread”) can be executed if available, or the CPU can be put to sleep until another task is ready.

Because an OS cannot presume that threads will behave cooperatively, threads are relatively resource-intensive and may be forcibly interrupted if they do not transfer control back to the kernel within an allotted time. If tasks could instead be presumed to behave cooperatively, it would be possible to create tasks that are almost free when compared to a traditional OS thread.

In other programming languages, these lightweight tasks are known as “coroutines” or ”goroutines”. In Rust, they are implemented with async. Async-await works by transforming each async function into an object called a future. When a future blocks on I/O the future yields, and the scheduler, called an executor, can select a different future to execute.

Compared to alternatives such as an RTOS, async can yield better performance and lower power consumption because the executor doesn’t have to guess when a future is ready to execute. However, program size may be higher than other alternatives, which may be a problem for certain space-constrained devices with very low memory. On the devices Embassy supports, such as STM32 and nRF, memory is generally large enough to accommodate the modestly-increased program size.

What is Embassy?

The Embassy project consists of several crates that you can use together or independently:

Executor

The embassy-executor is an async/await executor that generally executes a fixed number of tasks, allocated at startup, though more can be added later. The executor may also provide a system timer that you can use for both async and blocking delays. For less than one microsecond, blocking delays should be used because the cost of context-switching is too high and the executor will be unable to provide accurate timing.

Hardware Abstraction Layers

HALs implement safe Rust API which let you use peripherals such as USART, UART, I2C, SPI, CAN, and USB without having to directly manipulate registers.

Embassy provides implementations of both async and blocking APIs where it makes sense. DMA (Direct Memory Access) is an example where async is a good fit, whereas GPIO states are a better fit for a blocking API.

The Embassy project maintains HALs for select hardware, but you can still use HALs from other projects with Embassy.

  • embassy-stm32, for all STM32 microcontroller families.

  • embassy-nrf, for the Nordic Semiconductor nRF52, nRF53, nRF54, nRF91 series.

  • embassy-rp, for the Raspberry Pi RP2040 as well as RP235x microcontroller.

  • embassy-mspm0, for the Texas Instruments MSPM0 microcontrollers.

  • esp-hal, for the Espressif Systems ESP32 series of chips.

  • ch32-hal, for the WCH 32-bit RISC-V(CH32V) series of chips.

  • mpfs-hal, for the Microchip PolarFire SoC.

  • py32-hal, for the Puya Semiconductor PY32 series of chips.

Note
A common question is if one can use the Embassy HALs standalone. Yes, it is possible! There is no dependency on the executor within the HALs. You can even use them without async, as they implement both the Embedded HAL blocking and async traits.

Networking

The embassy-net network stack implements extensive networking functionality, including Ethernet, IP, TCP, UDP, ICMP and DHCP. Async drastically simplifies managing timeouts and serving multiple connections concurrently. Several drivers for WiFi and Ethernet chips can be found.

The embassy-ptp-driver crate defines a network-stack-independent interface for reading and adjusting PTP hardware clocks.

Bluetooth

  • The trouble crate provides a Bluetooth Low Energy 4.x and 5.x Host that runs on any microcontroller implementing the bt-hci traits (currently nRF52, nrf54, rp2040, rp23xx and esp32 and serial controllers are supported).

  • The nrf-softdevice crate provides Bluetooth Low Energy 4.x and 5.x support for nRF52 microcontrollers.

LoRa

lora-rs supports LoRa networking on a wide range of LoRa radios, fully integrated with a Rust LoRaWAN implementation. It provides four crates — lora-phy, lora-modulation, lorawan-encoding, and lorawan-device — and basic examples for various development boards. It has support for STM32WL wireless microcontrollers or Semtech SX127x transceivers, among others.

USB

embassy-usb implements a device-side USB stack. Implementations for common classes such as USB serial (CDC ACM) and USB HID are available, and a rich builder API allows building your own.

Bootloader and DFU

embassy-boot is a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks.

What is DMA?

For most I/O in embedded devices, the peripheral doesn’t directly support the transmission of multiple bytes at once, with CAN being a notable exception. Instead, the MCU must write each byte, one at a time, and then wait until the peripheral is ready to send the next. For high I/O rates, this can pose a problem if the MCU must devote an increasing portion of its time handling each byte. The solution to this problem is to use the Direct Memory Access controller.

The Direct Memory Access controller (DMA) is a controller that is present in MCUs that Embassy supports, including STM32 and nRF. The DMA allows the MCU to set up a transfer, either send or receive, and then wait for the transfer to complete. With DMA, once started, no MCU intervention is required until the transfer is complete, meaning that the MCU can perform other computation, or set up other I/O while the transfer is in progress. For high I/O rates, DMA can cut the time that the MCU spends handling I/O by over half. However, because DMA is more complex to set-up, it is less widely used in the embedded community. Embassy aims to change that by making DMA the first choice rather than the last. Using Embassy, there’s no additional tuning required once I/O rates increase because your application is already set-up to handle them.

Examples

Embassy provides examples for all HALs supported. You can find them in the examples/ folder.

Main loop example

use embassy_executor::Spawner;
use embassy_time::Timer;
use log::*;

#[embassy_executor::task]
async fn run() {
    loop {
        info!("tick");
        Timer::after_secs(1).await;
    }
}

#[embassy_executor::main]
async fn main(spawner: Spawner) {
    env_logger::builder()
        .filter_level(log::LevelFilter::Debug)
        .format_timestamp_nanos()
        .init();

    spawner.spawn(run().unwrap());
}

Embassy in the wild!

Here are known examples of real-world projects which make use of Embassy. Feel free to add more!

newer entries at the top

For beginners

The articles in this section are primarily aimed at users new to Embassy, showing how to get started, how to structure your project and other best practices.

Getting started

So you want to try Embassy, great! To get started, there are a few tools you need to install:

  • rustup - the Rust toolchain is needed to compile Rust code.

  • probe-rs - to flash the firmware on your device. If you already have other tools like OpenOCD setup, you can use that as well.

  • flip-link - to link certain example binaries with stack overflow protection.

If you don’t have any supported board, don’t worry: you can also run embassy on your PC using the std examples.

Getting a board with examples

Embassy supports many microcontroller families, but the quickest way to get started is by using a board which Embassy has existing example code for.

This list is non-exhaustive. If your board isn’t included here, check the examples folder to see if example code has been written for it.

nRF kits
RP2040 kits
ESP32

Running an example

First you need to clone the github repository;

git clone https://github.com/embassy-rs/embassy.git
cd embassy

Once you have a copy of the repository, find the examples folder for your board and build an example program. blinky is a good choice as all it does is blink an LED – the embedded world’s equivalent of “Hello World”.

cd examples/nrf52840
cargo build --bin blinky --release

Once you’ve confirmed you can build the example, connect your computer to your board with a debug probe and run it on hardware:

cargo run --bin blinky --release

If everything worked correctly, you should see a blinking LED on your board, and debug output similar to this on your computer:

    Finished dev [unoptimized + debuginfo] target(s) in 1m 56s
     Running `probe-rs run --chip STM32F407VGTx target/thumbv7em-none-eabi/debug/blinky`
(HOST) INFO  flashing program (71.36 KiB)
(HOST) INFO  success!
────────────────────────────────────────────────────────────────────────────────
0 INFO  Hello World!
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:18
1 INFO  high
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:23
2 INFO  low
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:27
3 INFO  high
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:23
4 INFO  low
└─ blinky::__embassy_main::task::{generator#0} @ src/bin/blinky.rs:27
Note
How does the cargo run command know how to connect to our board and program it? In each examples folder, there’s a .cargo/config.toml file which tells cargo to use probe-rs as the runner for ARM binaries in that folder. probe-rs handles communication with the debug probe and MCU. In order for this to work, probe-rs needs to know which chip it’s programming, so you’ll have to edit this file if you want to run examples on other chips.
It didn’t work!

If you are having issues when running cargo run --release, please check the following:

  • You are specifying the correct --chip on the command line, OR

  • You have set .cargo/config.toml’s run line to the correct chip, AND

  • You have changed examples/Cargo.toml’s HAL (e.g. embassy-stm32) dependency’s feature to use the correct chip (replace the existing stm32xxxx feature)

At this point the project should run. If you do not see a blinky LED for blinky, for example, be sure to check the code is toggling your board’s LED pin.

If you are trying to run an example with cargo run --release and you see the following output:

0.000000 INFO Hello World!
└─ <invalid location: defmt frame-index: 14>
0.000000 DEBUG rcc: Clocks { sys: Hertz(80000000), apb1: Hertz(80000000), apb1_tim: Hertz(80000000), apb2: Hertz(80000000), apb2_tim: Hertz(80000000), ahb1: Hertz(80000000), ahb2: Hertz(80000000), ahb3: Hertz(80000000) }
└─ <invalid location: defmt frame-index: 124>
0.000061 TRACE allocating type=Interrupt mps=8 interval_ms=255, dir=In
└─ <invalid location: defmt frame-index: 68>
0.000091 TRACE   index=1
└─ <invalid location: defmt frame-index: 72>

To get rid of the frame-index error add the following to your Cargo.toml:

[profile.release]
debug = 2

If you’re getting an extremely long error message containing something like the following:

error[E0463]: can't find crate for `std`
  |
  = note: the `thumbv6m-none-eabi` target may not support the standard library
  = note: `std` is required by `stable_deref_trait` because it does not declare `#![no_std]`

Make sure that you didn’t accidentally run cargo add probe-rs (which adds it as a dependency) instead of correctly installing probe-rs.

If you’re using a raspberry pi pico-w, make sure you’re running cargo run --bin wifi_blinky --release rather than the regular blinky. The pico-w’s on-board LED is connected to the WiFi chip, which needs to be initialized before the LED can be blinked.

If you’re using an rp2040 debug probe (e.g. the pico probe) and are having issues after running probe-rs info, unplug and reconnect the probe, letting it power cycle. Running probe-rs info is known to put the pico probe into an unusable state.

If you’re still having problems, check the FAQ, or ask for help in the Embassy Chat Room.

What’s next?

Congratulations, you have your first Embassy application running! Here are some suggestions for where to go from here:

A basic Embassy application

So you’ve got one of the examples running, but what now? Let’s go through a simple Embassy application for the nRF52 DK to understand it better.

Main

The full example can be found here.

Note
If you’re using VS Code and rust-analyzer to view and edit the examples, you may need to make some changes to .vscode/settings.json to tell it which project we’re working on. Follow the instructions commented in that file to get rust-analyzer working correctly.
Bare metal

The first thing you’ll notice are two attributes at the top of the file. These tell the compiler that the program has no access to std, and that there is no main function (because it is not run by an OS).

#![no_std]
#![no_main]
Dealing with errors

Then, what follows are some declarations on how to deal with panics and faults. During development, a good practice is to rely on defmt-rtt and panic-probe to print diagnostics to the terminal:

use defmt_rtt as _;
use panic_probe as _;
Interrupt binding

Drivers that complete work in an interrupt need that interrupt bound to their handler. Here, the button pin waits for edges through the GPIOTE interrupt:

bind_interrupts!(struct Irqs {
    GPIOTE => gpio::InterruptHandler<peripherals::P0_11>;
});

The Irqs struct is then passed to the driver’s constructor, which proves at compile time that the interrupt is bound.

Task declaration

After a bit of import declaration, the tasks run by the application should be declared:

// Declare async tasks
#[embassy_executor::task]
async fn blink(mut led: Output<'static>) {
    loop {
        // Timekeeping is globally available, no need to mess with hardware timers.
        led.set_high();
        Timer::after_millis(150).await;
        led.set_low();
        Timer::after_millis(150).await;
    }
}

An embassy task must be declared async, and may NOT take generic arguments. In this case, we are handed the LED that should be blinked and the interval of the blinking.

Note
Notice that there is no busy waiting going on in this task. It is using the Embassy timer to yield execution, allowing the microcontroller to sleep in between the blinking.
Main

The main entry point of an Embassy application is defined using the #[embassy_executor::main] macro. The entry point is passed a Spawner, which it can use to spawn other tasks.

We then initialize the HAL with a default config, which gives us a Peripherals struct we can use to access the MCU’s various peripherals. In this case, we want to configure one of the pins as a GPIO output driving the LED:

#[embassy_executor::main]
async fn main(spawner: Spawner) {
    // Initialize the embassy-nrf HAL.
    let p = embassy_nrf::init(Default::default());

    // Spawned tasks run in the background, concurrently.
    let led = Output::new(p.P0_13, Level::Low, OutputDrive::Standard);
    spawner.spawn(blink(led).unwrap());

    let mut button = Input::new_async(p.P0_11, Irqs, Pull::Up);
    loop {
        // Asynchronously wait for GPIO events, allowing other tasks
        // to run, or the core to sleep.
        button.wait_for_low().await;
        info!("Button pressed!");
        button.wait_for_high().await;
        info!("Button released!");
    }
}

What happens when the blinker task has been spawned and main returns? Well, the main entry point is actually just like any other task, except that you can only have one and it takes some specific type arguments. The magic lies within the #[embassy_executor::main] macro. The macro does the following:

  1. Creates an Embassy Executor

  2. Defines a main task for the entry point

  3. Runs the executor spawning the main task

There is also a way to run the executor without using the macro, in which case you have to create the Executor instance yourself.

The Cargo.toml

The project definition needs to contain the embassy dependencies:

embassy-executor = { version = "0.10.0", path = "../../../embassy-executor", features = ["defmt", "platform-cortex-m", "executor-thread"] }
embassy-time = { version = "0.5.1", path = "../../../embassy-time", features = ["defmt"] }
embassy-nrf = { version = "0.11.0", path = "../../../embassy-nrf", features = ["defmt", "nrf52840", "time-driver-rtc1"] }

Depending on your microcontroller, you may need to replace embassy-nrf with something else (embassy-stm32 for STM32. Remember to update feature flags as well).

In this particular case, the nrf52840 chip is selected, and the RTC1 peripheral is used as the time driver.

Project Structure

There are many ways to configure embassy and its components for your exact application. The examples directory for each chipset demonstrates how your project structure should look. Let’s break it down:

The toplevel file structure of your project should look like this:

{} = Maybe

my-project
|- .cargo
|  |- config.toml
|- src
|  |- main.rs
|- build.rs
|- Cargo.toml
|- {memory.x}
|- rust-toolchain.toml

.cargo/config.toml

This directory/file describes what platform you’re on, and configures probe-rs to deploy to your device.

Here is a minimal example:

[target.thumbv6m-none-eabi] # <-change for your platform
runner = 'probe-rs run --chip STM32F031K6Tx' # <- change for your chip

[build]
target = "thumbv6m-none-eabi" # <-change for your platform

[env]
DEFMT_LOG = "trace" # <- can change to info, warn, or error

build.rs

This is the build script for your project. It links defmt (what is defmt?) and the memory.x file if needed. This file is pretty specific for each chipset, just copy and paste from the corresponding example.

Cargo.toml

This is your manifest file, where you can configure all of the embassy components to use the features you need.

Features
Time
  • tick-hz-x: Configures the tick rate of embassy-time. Higher tick rate means higher precision, and higher CPU wakes.

  • defmt-timestamp-uptime: defmt log entries will display the uptime in seconds.

…​more to come

memory.x

This file outlines the flash/ram usage of your program. It is especially useful when using nrf-softdevice on an nRF5x.

Here is an example for using S140 with an nRF52840:

MEMORY
{
  /* NOTE 1 K = 1 KiBi = 1024 bytes */
  /* These values correspond to the NRF52840 with Softdevices S140 7.0.1 */
  FLASH : ORIGIN = 0x00027000, LENGTH = 868K
  RAM : ORIGIN = 0x20020000, LENGTH = 128K
}

rust-toolchain.toml

This file configures the rust version and configuration to use.

A minimal example:

[toolchain]
channel = "1.85" # <- as of writing, this is the exact rust version embassy uses
components = [ "rust-src", "rustfmt" ] # <- optionally add "llvm-tools-preview" for some extra features like "cargo size"
targets = [
    "thumbv6m-none-eabi" # <- change for your platform
]

Starting a new project

Once you’ve successfully run some example projects, the next step is to make a standalone Embassy project.

Tools for generating Embassy projects

CLI
cargo-generate