embassy Documentation

Modern embedded framework, using Rust and async.

9,971 stars Rust Rust 122 files · ~60,320 tokens #async#drivers#embedded#executor#hal#rust
RAW Doc

Technical Documentation: embassy-rs/embassy

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)

Embassy

Embassy is the next-generation framework for embedded applications. Write safe, correct, and energy-efficient embedded code faster, using the Rust programming language, its async facilities, and the Embassy libraries.

[Documentation](https://embassy.dev/book/index.html) - [API reference](https://docs.embassy.dev/) - [Website](https://embassy.dev/) - [Chat](https://matrix.to/#/#embassy-rs:matrix.org)

Rust + async ❤️ embedded

The Rust programming language is blazingly fast and memory-efficient, with no runtime, garbage collector, or OS. It catches a wide variety of bugs at compile time, thanks to its full memory- and thread-safety, and expressive type system.

Rust's async/await allows for unprecedentedly easy and efficient multitasking in embedded systems. Tasks get transformed at compile time into state machines that get run cooperatively. It requires no dynamic memory allocation and runs on a single stack, so no per-task stack size tuning is required. It obsoletes the need for a traditional RTOS with kernel context switching, and is faster and smaller than one!

Batteries included

  • Hardware Abstraction Layers

    • HALs implement safe, idiomatic Rust APIs to use the hardware capabilities, so raw register manipulation is not needed. 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 and nRF91 series.
    • embassy-rp, for the Raspberry Pi RP2040 and RP23xx microcontrollers.
    • embassy-mspm0, for the Texas Instruments MSPM0 microcontrollers.
    • embassy-mcxa, for NXP's MCX-A series of microcontrollers.
    • esp-rs, for the Espressif Systems ESP32 series of chips.
      • Embassy HAL support for Espressif chips, as well as Async Wi-Fi, Bluetooth, and ESP-NOW, is being developed in the esp-rs/esp-hal repository.
    • 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 microcontrollers.
    • ra-hal, for the Renesas RA family of microcontrollers.
  • Time that Just Works -
    No more messing with hardware timers. embassy_time provides Instant, Duration, and Timer types that are globally available and never overflow.

  • Real-time ready -
    Tasks on the same async executor run cooperatively, but you can create multiple executors with different priorities so that higher priority tasks preempt lower priority ones. See the example.

  • Low-power ready -
    Easily build devices with years of battery life. The async executor automatically puts the core to sleep when there's no work to do. Tasks are woken by interrupts, there is no busy-loop polling while waiting.

  • 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.
    embassy-ptp-driver provides 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.
    • The embassy-stm32-wpan crate provides Bluetooth Low Energy 5.x support for stm32wb microcontrollers.
  • LoRa -
    The lora-rs project provides an async LoRa and LoRaWAN stack that works well on Embassy.

  • 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.

Sneak peek

rust,ignore
use defmt::info;
use embassy_executor::Spawner;
use embassy_time::{Duration, Timer};
use embassy_nrf::gpio::{AnyPin, Input, Level, Output, OutputDrive, Pin, Pull};
use embassy_nrf::{Peri, Peripherals};

// Declare async tasks
#[embassy_executor::task]
async fn blink(pin: Peri<'static, AnyPin>) {
    let mut led = Output::new(pin, Level::Low, OutputDrive::Standard);

    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;
    }
}

// Main is itself an async task as well.
#[embassy_executor::main]
async fn main(spawner: Spawner) {
    let p = embassy_nrf::init(Default::default());

    // Spawned tasks run in the background, concurrently.
    spawner.spawn(blink(p.P0_13.into()).unwrap());

    let mut button = Input::new(p.P0_11, 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!");
    }
}

Examples

Examples are found in the
examples/ folder separated by the chip manufacturer they are designed to run on. For example:

  • examples/nrf52840 run on the
    nrf52840-dk board (PCA10056) but should be easily adaptable to other nRF52 chips and boards.
  • examples/nrf5340 run on the nrf5340-dk board (PCA10095).
  • examples/stm32xx for the various STM32 families.
  • examples/rp are for the RP2040 and RP235x chips.
  • examples/mcxa266 run on the FRDM-MCXA266 board.
  • examples/mcxa577 run on the FRDM-MCXA577 board.
  • examples/std are designed to run locally on your PC.

Running examples

  • Install probe-rs following the instructions at https://probe.rs.
  • Change directory to the sample's base directory. For example:
bash
cd examples/nrf52840
  • Ensure Cargo.toml sets the right feature for the name of the chip you are programming.
    If this name is incorrect, the example may fail to run or immediately crash
    after being programmed.

  • Ensure .cargo/config.toml contains the name of the chip you are programming.

  • Run the example

For example:

bash
cargo run --release --bin blinky

For more help getting started, see Getting Started and Running the Examples.

Developing Embassy with Rust Analyzer-based editors

The Rust Analyzer is used by Visual Studio Code
and others. Given the multiple targets that Embassy serves, there is no Cargo workspace file. Instead, the Rust Analyzer
must be told of the target project to work with. In the case of Visual Studio Code,
please refer to the .vscode/settings.json file's rust-analyzer.linkedProjectssetting.

Minimum supported Rust version (MSRV)

Embassy is guaranteed to compile on latest stable Rust. It might
compile with older versions, but that may change in any new patch release.

Why the name?

EMBedded ASYnc! :)

License

Embassy is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.


Overview (`cyw43-firmware/README.md`)

WiFi + Bluetooth firmware blobs

Firmware obtained from https://github.com/georgerobotics/cyw43-driver/tree/main/firmware

Licensed under the Infineon Permissive Binary License

Changelog

  • 2023-08-21: synced with a1dc885 - Update 43439 fw + clm to come from wb43439A0_7_95_49_00_combined.h + add Bluetooth firmware
  • 2023-07-28: synced with ad3bad0 - Update 43439 fw from 7.95.55 to 7.95.62

Notes

If you update these files, please update the lengths in the tests/rp/src/bin/cyw43_perf.rs test (which relies on these files running from RAM).


Overview (`cyw43-pio/README.md`)

cyw43-pio

RP2040 PIO driver for the nonstandard half-duplex SPI used in the Pico W. The PIO driver offloads SPI communication with the WiFi chip and improves throughput.


Overview (`cyw43/README.md`)

cyw43

Rust driver for the CYW43439 wifi+bluetooth chip. Implementation based on Infineon/wifi-host-driver.

Works on the following boards:

  • Raspberry Pi Pico W (RP2040)
  • Raspberry Pi Pico 2 W (RP2350A)
  • Pimoroni Pico Plus 2 W (RP2350B)
  • Any board with Raspberry Pi RM2 radio module.
  • Any board with the CYW43439 chip, and possibly others if the protocol is similar enough.

Features

Working:

  • WiFi support
    • Station mode (joining an AP).
    • AP mode with open, WPA2, WPA3, and WPA2/WPA3 transition-mode security. WPA3 requires compatible CYW43 firmware and client support.
    • Scanning
    • Sending and receiving Ethernet frames.
    • Using the default MAC address.
    • embassy-net integration.
    • RP2040 PIO driver for the nonstandard half-duplex SPI used in the Pico W.
    • Using IRQ for device events, no busy polling.
    • GPIO support (for LED on the Pico W).
  • Bluetooth support
    • Bluetooth Classic + LE HCI commands.
    • Concurrent operation with WiFi.
    • Implements the bt-hci controller traits.
    • Works with the TrouBLE bluetooth LE stack. Check its repo for examples using cyw43.

Running the WiFi examples

  • Install probe-rs following the instructions at https://probe.rs.
  • cd examples/rp

Example 1: Scan the wifi stations

  • cargo run --release --bin wifi_scan

Example 2: Create an access point (IP and credentials in the code)

  • cargo run --release --bin wifi_ap_tcp_server

Example 3: Connect to an existing network and create a server

  • cargo run --release --bin wifi_tcp_server

After a few seconds, you should see that DHCP picks up an IP address like this

text
11.944489 DEBUG Acquired IP configuration:
11.944517 DEBUG    IP address:      192.168.0.250/24
11.944620 DEBUG    Default gateway: 192.168.0.33
11.944722 DEBUG    DNS server 0:    192.168.0.33

This example implements a TCP echo server on port 1234. You can try connecting to it with:

text
nc 192.168.0.250 1234

Send it some data, you should see it echoed back and printed in the firmware's logs.


Overview (`docs/README.md`)

embassy docs

The documentation hosted at https://embassy.dev/book. Building the documentation requires the asciidoctor tool, and can built running make in this folder:

text
make

Then open the generated file thebook/index.html.

License

The Embassy Docs (this folder) is distributed under the following licenses:

  • The code samples and free-standing Cargo projects contained within these docs are licensed under the terms of both the MIT License and the Apache License v2.0.
  • The written prose contained within these docs are licensed under the terms of the Creative Commons CC-BY-SA v4.0 license.

Copies of the licenses used by this project may also be found here:


Overview (`embassy-ambiq/README.md`)

embassy-ambiq

Support for Ambiq Apollo3 microcontrollers.

Status

  • Supported: GPIO, Time Driver (STIMER/CTIMER0)
  • Primary Target: Apollo3 Blue / SparkFun Artemis

Quirks

Time Drivers

Timer features (time-driver-stimer-* or time-driver-ctimer0) bundle the hardware timer, clock source, and embassy-time tick rate together. Enable exactly one.

  • time-driver-stimer-xtal-32768: Standard continuous timekeeping.
  • time-driver-ctimer0: Experimental one-shot mode (alarms do not re-arm).

SVL Bootloader (SparkFun Artemis)

The Artemis SVL bootloader hands off execution at 0x10000. If you are flashing via UART/SVL, you can enable the svl-vtor feature. This repoints the vector table to 0x10000 during embassy_ambiq::init(). Do not enable this if you are using a raw SWD probe at 0x0.

PAC

The apollo3-pac is currently at apollo3-pac-rs.


Overview (`embassy-boot-nrf/README.md`)

embassy-boot-nrf

An Embassy project.

An adaptation of embassy-boot for nRF.

Features

  • Load applications with or without the softdevice.
  • Configure bootloader partitions based on linker script.
  • Using watchdog timer to detect application failure.

Working with a SoftDevice

When a SoftDevice is present, it handles starting the bootloader and the application as needed.

The SoftDevice architecture supports the bootloader via a configurable base address, referred to as BOOTLOADERADDR, in the application flash region. This address can be specified either:

  1. At the MBR_BOOTLOADER_ADDR location in flash memory (defined in nrf_mbr.h), or
  2. In the UICR.NRFFW[0] register.

The UICR.NRFFW[0] register is used only if MBR_BOOTLOADER_ADDR has its default value of 0xFFFFFFFF. This bootloader relies on the latter approach.

In the memory.x linker script, there is a section .uicr_bootloader_start_address (origin 0x10001014, length 0x4) that stores the BOOTLOADERADDR value.
Ensure that __bootloader_start is set to the origin address of the bootloader partition.

When a bootloader is present, the SoftDevice forwards interrupts to it and executes the bootloader reset handler, defined in the bootloader's vector table at BOOTLOADERADDR.

Once the bootloader loads the application, the SoftDevice initiates the Application Reset Handler, defined in the application’s vector table at APP_CODE_BASE hardcoded in the SoftDevice.
The active partition's origin must match the APP_CODE_BASE value hardcoded within the SoftDevice. This value can be found in the release notes for each SoftDevice version.


Overview (`embassy-boot-rp/README.md`)

embassy-boot-rp

An Embassy project.

An adaptation of embassy-boot for RP2040 and RP235x.

NOTE: The applications using this bootloader should not link with the link-rp.x linker script.

Features

  • Configure bootloader partitions based on linker script.
  • Load applications from active partition.

Overview (`embassy-boot-stm32/README.md`)

embassy-boot-stm32

An Embassy project.

An adaptation of embassy-boot for STM32.

Features

  • Configure bootloader partitions based on linker script.
  • Load applications from active partition.

Overview (`embassy-boot/README.md`)

embassy-boot

An Embassy project.

A lightweight bootloader supporting firmware updates in a power-fail-safe way, with trial boots and rollbacks.

The bootloader can be used either as a library or be flashed directly with the default configuration derived from linker scripts.

By design, the bootloader does not provide any network capabilities. Networking capabilities for fetching new firmware can be provided by the user application, using the bootloader as a library for updating the firmware, or by using the bootloader as a library and adding this capability yourself.

Overview

The bootloader divides the storage into 4 main partitions, configurable when creating the bootloader instance or via linker scripts:

  • BOOTLOADER - Where the bootloader is placed. The bootloader itself consumes about 8kB of flash, but if you need to debug it and have space available, increasing this to 24kB will allow you to run the bootloader with probe-rs.
  • ACTIVE - Where the main application is placed. The bootloader will attempt to load the application at the start of this partition. The minimum size required for this partition is the size of your application.
  • DFU - Where the application-to-be-swapped is placed. This partition is written to by the application. This partition must be at least 1 page bigger than the ACTIVE partition.
  • BOOTLOADER STATE - Where the bootloader stores the current state describing if the active and dfu partitions need to be swapped.

For any partition, the following preconditions are required:

  • Partitions must be aligned on the page size.
  • Partitions must be a multiple of the page size.

The linker scripts for the application and bootloader look similar, but the FLASH region must point to the BOOTLOADER partition for the bootloader, and the ACTIVE partition for the application.

For more details on the bootloader, see the documentation.

Hardware support

The bootloader supports different hardware in separate crates:

  • embassy-boot-nrf - for the nRF microcontrollers.
  • embassy-boot-rp - for the RP2040, RP235x microcontrollers.
  • embassy-boot-stm32 - for the STM32 microcontrollers.

Overview (`embassy-crypto-rand/README.md`)

embassy-crypto-rand

Random number generator driver for embassy-crypto,
backed by the operating system's secure random source through
getrandom.

Depending on this crate registers getrandom as the global
embassy_crypto::driver::Rng.

toml
[dependencies]
embassy-crypto = "0.1"
embassy-crypto-rand = "0.1"

To make sure Rust links this crate, add a dummy use like this:

rust
use embassy_crypto_rand as _;

Overview (`embassy-crypto-rustcrypto/README.md`)

embassy-crypto-rustcrypto

Software drivers for embassy-crypto,
built on the RustCrypto crates.

Each driver is behind one Cargo feature named embassy-crypto-<operation>
(embassy-crypto-sha256, embassy-crypto-aes128-gcm, embassy-crypto-p256-ecdsa, ...).
Enabling it registers this crate's implementation as the global driver for that
operation, and pulls in only the RustCrypto crates it needs. The all feature
enables every driver.

toml
[dependencies]
embassy-crypto = "0.1"
embassy-crypto-rustcrypto = { version = "0.1", features = ["embassy-crypto-sha256", "embassy-crypto-aes128-gcm"] }

To make sure Rust links this crate, add a dummy use like this:

rust
use embassy_crypto_rustcrypto as _;

Overview (`embassy-crypto-stub/README.md`)

embassy-crypto-stub

Stub drivers for embassy-crypto.

This crate registers a driver for every operation, exactly like
embassy-crypto-rustcrypto, but every
implementation panics with unreachable!(). It is a placeholder for builds
where no real crypto backend (hardware, hand-written ASM, RustCrypto) is
available, so that code linking against embassy-crypto still compiles and
links. Any actual crypto operation traps at runtime.

Each driver is behind one Cargo feature named embassy-crypto-<operation>
(embassy-crypto-sha256, embassy-crypto-aes128-gcm, embassy-crypto-p256-ecdsa, ...).
The features are empty and exist only so dependents can name them. The all
feature enables every driver.

toml
[dependencies]
embassy-crypto = "0.1"
embassy-crypto-stub = { version = "0.1", features = ["embassy-crypto-sha256", "embassy-crypto-aes128-gcm"] }

To make sure Rust links this crate, add a dummy use like this:

rust
use embassy_crypto_stub as _;

Overview (`embassy-crypto-test/README.md`)

embassy-crypto-test

Known-answer test suites for embassy-crypto drivers.

Every suite drives the public embassy-crypto API, so it tests whichever
driver the binary links.

rust
use embassy_crypto_rustcrypto as _; // or a HAL that registers drivers

embassy_crypto_test::sha256().unwrap();
embassy_crypto_test::aes128_gcm().unwrap();

Vectors

  • Wycheproof for HMAC, HKDF, AES-CBC, GCM,
    CCM, CMAC, ChaCha20-Poly1305, ECDH, ECDSA verification, X25519 and Ed25519 verification. build.rs clones the
    repository at a pinned commit into OUT_DIR. Set WYCHEPROOF_DIR to an
    existing checkout to build offline.
  • Generated at build time with the RustCrypto crates: plain digests, AES-ECB, AES-CTR, ChaCha8/12/20, ChaCha8/12-Poly1305, CCM with a long AAD, curve arithmetic, X25519 key generation and Ed25519 signing.
  • Vectors are included for some algorithms not covered by embassy-crypto, to
    help HALs test: raw RSA, P-192, P-224, P-521 and secp256k1.

Overview (`embassy-embedded-hal/README.md`)

embassy-embedded-hal

Collection of utilities to use embedded-hal and embedded-storage traits with Embassy.

  • Shared SPI and I2C buses, both blocking and async, with a SetConfig trait allowing changing bus configuration (e.g. frequency) between devices on the same bus.
  • Async utilities
    • Adapters to convert from blocking to (fake) async.
    • Adapters to insert yields on trait operations.
  • Flash utilities
    • Split a flash memory into smaller partitions.
    • Concatenate flash memories together.
    • Simulated in-memory flash.

Overview (`embassy-executor-macros/README.md`)

embassy-executor-macros

An Embassy project.

NOTE: Do not use this crate directly. The macros are re-exported by embassy-executor.


Overview (`embassy-executor-timer-queue/README.md`)

embassy-executor-time-queue

This crate defines the timer queue item that embassy-executor provides, and a way to access it, for
executor-integrated timer queues. The crate decouples the release cycle of embassy-executor from
that of the queue implementations'.

As a HAL implementer, you only need to depend on this crate if you want to implement executor-integrated
timer queues yourself, without using embassy-time-queue-utils.

As a HAL user, you should not need to depend on this crate.


Overview (`embassy-executor/README.md`)

embassy-executor

An async/await executor designed for embedded usage.

  • No alloc, no heap needed.
  • Tasks are statically allocated. Each task gets its own static, with the exact size to hold the task (or multiple instances of it, if using pool_size) calculated automatically at compile time. If tasks don't fit in RAM, this is detected at compile time by the linker. Runtime panics due to running out of memory are not possible.
  • No "fixed capacity" data structures, executor works with 1 or 1000 tasks without needing config/tuning.
  • Integrated timer queue: sleeping is easy, just do Timer::after_secs(1).await;.
  • No busy-loop polling: CPU sleeps when there's no work to do, using interrupts or WFE/SEV.
  • Efficient polling: a wake will only poll the woken task, not all of them.
  • Fair: a task can't monopolize CPU time even if it's constantly being woken. All other tasks get a chance to run before a given task gets polled for the second time.
  • Creating multiple executor instances is supported, to run tasks with multiple priority levels. This allows higher-priority tasks to preempt lower-priority tasks.

Platforms

The executor requires a "platform" to be defined to work. A platform defines the following things:

  • The main loop, which typically consists of an infinite loop of polling the executor then sleeping the current thread/core in a platform-specific way.
  • A "pender" callback, which must cause the executor's thread/core to exit sleep so the executor gets polled again. This is called when a task running in the executor is woken.

The embassy-executor crate ships with support for some commonly used platforms, see the crate's feature documentation.

Chip-specific executor platform implementations are maintained in their respective HALs:

  • embassy-rp: multicore support. Enabled with the executor-interrupt or executor-thread features.
  • embassy-stm32: automatic low-power sleep support. Enabled with the executor-interrupt or executor-thread features.
  • embassy-mcxa: automatic low-power sleep support. Enabled with the executor-platform feature.
  • esp-rtos: ESP32 RTOS support, multicore support. Enabled with the embassy feature.

To use the executor, you must provide exactly one platform implementation, either from this crate, a HAL crate, or a custom one.

Implementing a custom platform

To implement your own custom platform, e.g. on top of an RTOS, do the following:

  1. define the __pender callback.
rust,ignore
#[unsafe(export_name = "__pender")]
fn __pender(context: *mut ()) {
    // `context` is the argument passed to `raw::Executor::new`. Here we're using it
    // to pass a handle to the RTOS task but you can use it for anything.
    my_rtos::notify_task(context as _);
}
  1. Wrap the raw::Executor into your own Executor struct that defines the main loop.
rust,ignore
pub struct Executor {
    inner: raw::Executor,
    not_send: PhantomData<*mut ()>,
}

impl Executor {
    pub fn new() -> Self {
        Self {
            inner: raw::Executor::new(my_rtos::task_get_current() as _),
            not_send: PhantomData,
        }
    }

    pub fn run(&'static mut self, init: impl FnOnce(Spawner)) -> ! {
        init(self.inner.spawner());

        loop {
            unsafe { self.inner.poll() }
            my_rtos::task_wait_for_notification();
        }
    }
}

Overview (`embassy-futures/README.md`)

embassy-futures

An Embassy project.

Utilities for working with futures, compatible with no_std and not using alloc. Optimized for code size,
ideal for embedded systems.

Interoperability

Futures from this crate can run on any executor.


Overview (`embassy-hal-internal/README.md`)

embassy-hal-internal

An Embassy project.

Internal implementation details for Embassy HALs. DO NOT USE DIRECTLY. Embassy HALs (embassy-nrf, embassy-stm32, embassy-rp) already reexport
everything you need to use them effectively.


Overview (`embassy-imxrt/README.md`)

Embassy iMXRT HAL

Introduction

HALs implement safe, idiomatic Rust APIs to use the hardware capabilities, so
raw register manipulation is not needed.

The Embassy iMXRT HAL targets the NXP iMXRT Family of MCUs. The HAL implements
both blocking and async APIs for many peripherals. The benefit of using the
async APIs is that the HAL takes care of waiting for peripherals to complete
operations in low power mode and handling of interrupts, so that applications
can focus on business logic.

NOTE: The Embassy HALs can be used both for non-async and async operations. For
async, you can choose which runtime you want to use.

For a complete list of available peripherals and features, see the
embassy-imxrt documentation.

Hardware support

The embassy-imxrt HAL currently supports two main variants of the iMXRT
family:

Several peripherals are supported and tested on both supported chip variants. To
check what's available, make sure to the MCU you're targetting in the top menu
in the documentation.

TrustZone support

TrustZone support is yet to be implemented.

Time driver

If the time-driver feature is enabled, the HAL uses the RTC peripheral as a
global time driver for embassy-time,
with a tick rate of 32768 Hz.

Embedded-hal

The embassy-imxrt HAL implements the traits from
embedded-hal (v0.2 and 1.0) and
embedded-hal-async, as well as
embedded-io and
embedded-io-async.

Interoperability

This crate can run on any executor.

Optionally, some features requiring
embassy-time can be activated with
the time feature. If you enable it, you must link an embassy-time driver in
your project.


Overview (`embassy-mcxa/README.md`)

Embassy NXP MCX-A MCUs HAL

A Hardware Abstraction Layer (HAL) for the NXP MCX-A family of
microcontrollers using the Embassy async framework. This HAL provides
safe, idiomatic Rust interfaces for GPIO, UART, and OSTIMER
peripherals.


Overview (`embassy-microchip/README.md`)

Embassy Microchip HAL

HALs implement safe, idiomatic Rust APIs to use the hardware capabilities, so
raw register manipulation is not needed.

The Embassy Microchip HAL targets the Microchip MEC and CEC Family of MCUs. The
HAL implements both blocking and async APIs for many peripherals. The benefit of
using the async APIs is that the HAL takes care of waiting for peripherals to
complete operations in low power mode and handling of interrupts, so that
applications can focus on business logic.

NOTE: The Embassy HALs can be used both for non-async and async operations. For
async, you can choose which runtime you want to use.

For a complete list of available peripherals and features, see the
embassy-microchip documentation.


Overview (`embassy-mspm0/README.md`)

Embassy MSPM0 HAL

The embassy-mspm0 HAL aims to provide a safe, idiomatic hardware abstraction layer for all MSPM0 and MSPS003 chips.

  • Documentation (Important: use docs.embassy.dev rather than docs.rs to see the specific docs for the chip you’re using!)
  • Source
  • Examples

Embedded-hal

The embassy-mspm0 HAL implements the traits from embedded-hal (1.0) and embedded-hal-async, as well as embedded-io and embedded-io-async.

A note on feature flag names

Feature flag names for chips do not include temperature rating or distribution format.

Usually chapter 10 of your device's datasheet will explain the device nomenclature and how to decode it. Feature names in embassy-mspm0 only use the following from device nomenclature:

  • MCU platform
  • Product family
  • Device subfamily
  • Flash memory
  • Package type

This means for a part such as MSPM0G3507SPMR, the feature name is mspm0g3507pm. This also means that MSPM0G3507QPMRQ1 uses the feature mspm0g3507pm, since the Q1 parts are just qualified variants of the base G3507 with a PM (QFP-64) package.

Interoperability

This crate can run on any executor.


Overview (`embassy-net-adin1110/README.md`)

SPE ADIN1110 `embassy-net` integration

embassy-net integration for the Analog ADIN1110 SPI SPE ethernet chips.

What is SPE or Single Pair Ethernet / 10 BASE-T1L

SPE stands for Single Pair Ethernet. As the names implies, SPE uses differential signalling with 2 wires (a twisted-pair) in a cable as the physical medium.
SPE is full-duplex - it can transmit and receive ethernet packets at the same time. SPE is still ethernet, only the physical layer is different.

SPE also supports PoDL (Power over Data Line), power delivery from 0.5 up to 50 Watts, similar to PoE, but an additional hardware and handshake protocol are needed.

SPE has many link speeds but only 10 BASE-T1L is able to reach cable lengths up to 1000 meters in 2.4 Vpp transmit amplitude.
As of 2023, none of the standards were compatible with each other.
Thus 10 BASE-T1L won't work with a 10 BASE-T1S, 100 BASE-T1 or any standard x BASE-T.

In the industry SPE is also called APL (Advanced Physical Layer), and is based on the 10 BASE-T1L standard.

APL can be used in intrinsic safety applications/explosion hazardous areas which has its own name and standard called 2-WISE (2-wire intrinsically safe ethernet) IEC TS 60079-47:2021.

The 10 BASE-T1L standard and the ADIN1110 and ADIN2111 chips are designed to support intrinsic safety applications.

Supported SPI modes

These chips support two SPI modes. Generic and OPEN Alliance 10BASE-T1x MAC-PHY serial interface.

Both modes support with and without additional CRC.

NOTE: SPI Mode is selected by the hardware pins SPI_CFG0 and SPI_CFG1. Software can't detect nor change the mode.

Hardware

Other SPE chips

Testing

ADIN1110 library can tested on the host with a mock SPI driver.

$ cargo test --target x86_64-unknown-linux-gnu

Benchmark

Basic ping benchmark

rust,ignore
# ping <IP> -c 60

60 packets transmitted, 60 received, 0% packet loss, time 59066ms
rtt min/avg/max/mdev = 1.089/1.161/1.237/0.018 ms

# ping <IP> -s 1472 -M do -c 60

60 packets transmitted, 60 received, 0% packet loss, time 59066ms
rtt min/avg/max/mdev = 5.122/5.162/6.177/0.133 ms

HTTP load generator benchmark with oha

rust,ignore
# oha -c 1 http://<IP> -z 60s
Summary:
  Success rate: 50.00%
  Total:        60.0005 secs
  Slowest:      0.0055 secs
  Fastest:      0.0033 secs
  Average:      0.0034 secs
  Requests/sec: 362.1971

  Total data:   2.99 MiB
  Size/request: 289 B
  Size/sec:     51.11 KiB

Overview (`embassy-net-driver-channel/README.md`)

embassy-net-driver-channel

This crate provides a toolkit for implementing embassy-net drivers in a
higher level way than implementing the xarxa-driver Driver trait directly.

The Driver trait is polling-based. To implement it, you must write the packet receive/transmit state machines by
hand, and hook up the Wakers provided by embassy-net to the right interrupt handlers so that embassy-net
knows when to poll your driver again to make more progress.

With embassy-net-driver-channel you get a "channel-like" interface instead, where you can send/receive packets
to/from embassy-net. The intended usage is to spawn a "driver task" in the background that does this, passing
packets between the hardware and the channel.

A note about deadlocks

When implementing a driver using this crate, it might be tempting to write it in the most straightforward way:

rust,ignore
loop {
    // Wait for either..
    match select(
        // ... the chip signaling an interrupt, indicating a packet is available to receive, or
        irq_pin.wait_for_low(),
        // ... a packet to send appearing, i.e. embassy-net wants to send a packet
        tx_chan.tx(),
    ).await {
        Either::First(_) => {
            // a packet is ready to be received!
            let mut buf = rx_chan.rx_buf().await; // wait for an empty buffer from the stack
            buf.set_len(buf.capacity());
            let n = receive_packet_over_spi(&mut buf).await;
            buf.set_len(n);
            rx_chan.rx(buf).await;
        }
        Either::Second(buf) => {
            // a packet is ready to be sent!
            send_packet_over_spi(&buf).await;
        }
    }
}

However, this code has a latent deadlock bug. The symptom is it can hang at rx_chan.rx_buf().await under load.

The reason is that, under load, both the TX and RX queues can get full at the same time. When this happens, the embassy-net task stalls trying to send because the TX queue is full, therefore it stops processing packets in the RX queue and stops handing out empty buffers. Your driver task also stalls waiting for an empty buffer, therefore it stops processing packets in the TX queue.

The fix is to make sure to always service the TX queue while you're waiting for an empty buffer. For example, select on either "a packet to send is available" or "INT is low AND there is an empty buffer":

rust,ignore
loop {
    // Wait for either..
    match select(
        async {
            // ... the chip signaling an interrupt, indicating a packet is available to receive
            irq_pin.wait_for_low().await;
            // *AND* an empty buffer to receive it into...
            rx_chan.rx_buf().await
        },
        // ... or a packet to send appearing, i.e. embassy-net wants to send a packet
        tx_chan.tx(),
    ).await {
        Either::First(mut buf) => {
            // a packet is ready to be received!
            buf.set_len(buf.capacity());
            let n = receive_packet_over_spi(&mut buf).await;
            buf.set_len(n);
            rx_chan.rx(buf).await;
        }
        Either::Second(buf) => {
            // a packet is ready to be sent!
            send_packet_over_spi(&buf).await;
        }
    }
}

Examples

These embassy-net drivers are implemented using this crate. You can look at them for inspiration.

Interoperability

This crate can run on any executor.


Overview (`embassy-net-enc28j60/README.md`)

`embassy-net-enc28j60`

embassy-net integration for the Microchip ENC28J60 Ethernet chip.

Based on @japaric's enc28j60 crate.

Interoperability

This crate can run on any executor.


Overview (`embassy-net-esp-hosted/README.md`)

ESP-Hosted `embassy-net` integration

embassy-net integration for Espressif SoCs running the ESP-Hosted-Fg or ESP-Hosted-Mcu stack.

See examples directory for usage examples with the nRF52840.

Interoperability

This crate can run on any executor.

It supports any SPI driver implementing embedded-hal-async.


Overview (`embassy-net-nrf91/README.md`)

nRF91 `embassy-net` integration

embassy-net driver for Nordic nRF91-series cellular modems.

See the examples directory for usage examples with the nRF9160.

Interoperability

This crate can run on any executor.


Overview (`embassy-net-ppp/README.md`)

`embassy-net-ppp`

embassy-net integration for PPP over Serial.

Interoperability

This crate can run on any executor.

It supports any serial port implementing embedded-io-async.


Overview (`embassy-net-tuntap/README.md`)

`embassy-net` integration for Linux TUN/TAP interfaces.

embassy-net integration for for Linux TUN (IP medium) and TAP (Ethernet medium) interfaces.

Interoperability

This crate can run on any executor.


Overview (`embassy-net-wiznet/README.md`)

WIZnet `embassy-net` integration

embassy-net integration for the WIZnet SPI ethernet chips, operating in MACRAW mode.

See examples directory for usage examples with the rp2040 WIZnet W5500-EVB-Pico) module.

Supported chips

  • W5500
  • W5100S
  • W6100
  • W6300 (Single SPI only)

Interoperability

This crate can run on any executor.

It supports any SPI driver implementing embedded-hal-async.


Overview (`embassy-net/README.md`)

embassy-net

embassy-net is a no-std no-alloc async network stack, designed for embedded systems.

It uses the xarxa network stack, and adds convenient
async wrappers on top of it and implements the main loop for you.

Features

  • IPv4, IPv6
  • Ethernet, IP and IEEE 802.15.4 / 6LoWPAN mediums.
  • TCP, UDP, raw sockets, DNS, DHCPv4
  • TCP sockets implement the embedded-io async traits.
  • Multicast
  • Multiple interface support
  • Timestamping sent and received packets for e.g PTP

See the xarxa README for a detailed list of implemented and
unimplemented features of the network protocols.

Embassy-net focuses on the network/transport layer protocols up to TCP. Higher-level application layer protocols live in other crates built on top of embassy-net:

Hardware support

  • esp-radio for WiFi support ESP32 chips. Maintained by Espressif.
  • cyw43 for WiFi on CYW43xx chips, used in the Raspberry Pi Pico W
  • embassy-usb for Ethernet-over-USB (CDC NCM) support.
  • embassy-stm32 for the builtin Ethernet MAC in all STM32 chips (STM32F1, STM32F2, STM32F4, STM32F7, STM32H7, STM32H5).
  • embassy-net-wiznet for Wiznet SPI Ethernet MAC+PHY chips (W5100S, W5500)
  • embassy-net-enc28j60 for the Microchip ENC28J60 SPI Ethernet MAC+PHY chip.
  • embassy-net-adin1110 for the Analog Devices ADIN1110 SPI 10BASE-T1L single-pair Ethernet chip.
  • embassy-net-esp-hosted for using ESP32 chips with the esp-hosted firmware as WiFi adapters for another non-ESP32 MCU.
  • embassy-net-nrf91 for the cellular modem in Nordic nRF91-series chips.
  • embassy-net-ppp for PPP over Serial, useful with cellular modems or for a network link to a host computer.
  • embassy-nrf for IEEE 802.15.4 support on nrf chips.
  • embassy-stm32-wpan for IEEE 802.15.4 support on STM32WB chips.
  • embassy-net-tuntap for Linux TUN/TAP interfaces, useful for running on std platforms.

Examples

  • For usage with Embassy HALs and network chip drivers, search here for eth or wifi.
  • The esp-hal repo has examples for use on bare-metal ESP32 chips.
  • For usage on std platforms, see the std examples

Adding support for new hardware

To add embassy-net support for new hardware (i.e. a new Ethernet or WiFi chip, or
an Ethernet/WiFi MCU peripheral), you have to implement the xarxa-driver
Driver trait. Enable its async feature and implement Driver::register_waker: embassy-net
needs it to sleep until the driver has something new.

Drivers should depend only on xarxa-driver. Never on the main embassy-net crate. This allows
existing drivers to continue working for newer embassy-net major versions, without needing an
update, if the driver trait has not had breaking changes.

Interoperability

This crate can run on any executor.

embassy-time is used for timekeeping and timeouts. You must
link an embassy-time driver in your project to use this crate.


Overview (`embassy-nrf/README.md`)

Embassy nRF HAL

HALs implement safe, idiomatic Rust APIs to use the hardware capabilities, so raw register manipulation is not needed.

The Embassy nRF HAL targets the Nordic Semiconductor nRF family of hardware. The HAL implements both blocking and async APIs
for many peripherals. The benefit of using the async APIs is that the HAL takes care of waiting for peripherals to
complete operations in low power mode and handling interrupts, so that applications can focus on more important matters.

NOTE: The Embassy HALs can be used both for non-async and async operations. For async, you can choose which runtime you want to use.

For a complete list of available peripherals and features, see the embassy-nrf documentation.

Hardware support

The embassy-nrf HAL supports most variants of the nRF family:

Most peripherals are supported, but can vary between chip families. To check what's available, make sure to pick the MCU you're targeting in the top menu in the documentation.

For MCUs with TrustZone support, both Secure (S) and Non-Secure (NS) modes are supported. Running in Secure mode
allows running Rust code without a SPM or TF-M binary, saving flash space and simplifying development.

Time driver

If the time-driver-rtc1 feature is enabled, the HAL uses the RTC peripheral as a global time driver for embassy-time, with a tick rate of 32768 Hz.

Embassy-net driver

If the board supports IEEE 802.15.4 (see src/radio/mod.rs) the corresponding embassy-net driver can be enabled with the feature net-driver.

Embedded-hal

The embassy-nrf HAL implements the traits from embedded-hal (v0.2 and 1.0) and embedded-hal-async, as well as embedded-io and embedded-io-async.

Interoperability

This crate can run on any executor.

Optionally, some features requiring embassy-time can be activated with the time feature. If you enable it,
you must link an embassy-time driver in your project.

EasyDMA considerations

On nRF chips, peripherals can use the so called EasyDMA feature to offload the task of interacting
with peripherals. It takes care of sending/receiving data over a variety of bus protocols (TWI/I2C, UART, SPI).
However, EasyDMA requires the buffers used to transmit and receive data to reside in RAM. Unfortunately, Rust
slices will not always do so. The following example using the SPI peripheral shows a common situation where this might happen:

rust,ignore
// As we pass a slice to the function whose contents will not ever change,
// the compiler writes it into the flash and thus the pointer to it will
// reference static memory. Since EasyDMA requires slices to reside in RAM,
// this function call will fail.
let result = spim.write_from_ram(&[1, 2, 3]);
assert_eq!(result, Err(Error::BufferNotInRAM));

// The data is still static and located in flash. However, since we are assigning
// it to a variable, the compiler will load it into memory. Passing a reference to the
// variable will yield a pointer that references dynamic memory, thus making EasyDMA happy.
// This function call succeeds.
let data = [1, 2, 3];
let result = spim.write_from_ram(&data);
assert!(result.is_ok());

Each peripheral struct which uses EasyDMA (Spim, Uarte, Twim) has two variants of their mutating functions:

  • Functions with the suffix (e.g. write_from_ram, transfer_from_ram) will return an error if the passed slice does not reside in RAM.
  • Functions without the suffix (e.g. write, transfer) will check whether the data is in RAM and copy it into memory prior to transmission.

Since copying incurs a overhead, you are given the option to choose from _from_ram variants which will
fail and notify you, or the more convenient versions without the suffix which are potentially a little bit
more inefficient. Be aware that this overhead is not only in terms of instruction count but also in terms of memory usage
as the methods without the suffix will be allocating a statically sized buffer (up to 512 bytes for the nRF52840).

Note that the methods that read data like read and transfer_in_place do not have the corresponding _from_ram variants as
mutable slices always reside in RAM.


Overview (`embassy-ptp-driver/README.md`)

embassy-ptp-driver

This crate defines the common timestamp type and adjustable clock trait for PTP
hardware clocks. Hardware implementations and clock-synchronization engines can
depend on this crate without depending on each other or on embassy-net.

Packet timestamp transport and its timestamp type remain independently owned by
xarxa-driver. An integration crate may convert between timestamps when
the packet timestamp source and adjustable clock are the same hardware time
domain.

The clock here is also distinct from embassy-time-driver: executor time is a
global, monotonic scheduling clock, while a PTP hardware clock has an arbitrary
epoch and is adjusted while it is being synchronized.

Interoperability

This crate can run on any executor.


Overview (`embassy-rp/README.md`)

Embassy RP HAL

HALs implement safe, idiomatic Rust APIs to use the hardware capabilities, so raw register manipulation is not needed.

The embassy-rp HAL targets the Raspberry Pi RP2040 as well as RP235x microcontroller. The HAL implements both blocking and async APIs
for many peripherals. The benefit of using the async APIs is that the HAL takes care of waiting for peripherals to
complete operations in low power mode and handling interrupts, so that applications can focus on more important matters.

`embassy-time` time driver

If the time-driver feature is enabled, the HAL uses the TIMER peripheral as a global time driver for embassy-time, with a tick rate of 1MHz.

Embedded-hal

The embassy-rp HAL implements the traits from embedded-hal (v0.2 and 1.0) and embedded-hal-async, as well as embedded-io and embedded-io-async.

Interoperability

This crate can run on any executor.

Optionally, some features requiring embassy-time can be activated with the time-driver feature. If you enable it,
you must link an embassy-time driver in your project.


Overview (`embassy-stm32-neochrom/README.md`)

embassy-stm32-neochrom

Embassy integration for ST NeoChrom (GPU2D) using the NemaGFX middleware via stm32-bindings.

Status

Hardware-validated on STM32N6 (NUCLEO-N6570/N6570-DK): GPU2D init, the cache-hold
handshake, and batched clear/fill/stroke/blit operations all work end-to-end,
including driving an LTDC panel (see examples/stm32n6/src/bin/neochrom_lcd.rs).
The async completion path (end_frame_async(), the interrupt-driven waker in
gpu2d_bridge.rs) is implemented and builds clean but has not yet been
exercised on real hardware — end_frame() (blocking) is the exercised path.
U5 and H7RS chip features are wired up in Cargo.toml (same NemaGFX core,
different prebuilt library) but have no example or hardware validation yet.

Local development

This crate depends on stm32-bindings (>= 0.3.1, the first release with the
NemaGFX bindings), published on crates.io — no local [patch] needed.

Build (example chip feature):

bash
cd embassy-stm32-neochrom
cargo check --target thumbv8m.main-none-eabihf --features stm32n657x0,stub-gpu2d

Features

NemaGFX ships one prebuilt library per CPU core / GPU variant; stm32-bindings
forwards these as neochrom-* presets, and each chip feature below pulls in
exactly one automatically — enable exactly one chip feature, since
stm32-bindings's build.rs rejects linking multiple NemaGFX core variants
at once.

Feature NemaGFX preset GPU variant Typical parts Status
stm32n657x0 / stm32n655x0 / stm32n647x0 neochrom-m55 NeoChrom STM32N6xx hardware-validated
stm32u599nj neochrom-m33-revc NeoChrom STM32U5x7/x9 untested
stm32u5g9nj neochrom-m33-nemapvg NeoChromVG STM32U5F9/U5G9 untested
stm32h7s7z8 / stm32h7r7z8 neochrom-m7 NeoChrom STM32H7R7/H7S7 untested
stub-gpu2d — — — default; CI / link tests, no hardware needed
embedded-graphics — — — NeoChromTarget embedded-graphics DrawTarget wrapper
defmt / log — — — Logging backend

Disable default-features and stub-gpu2d when wiring the real GPU2D peripheral on hardware.

Driver highlights

  • Batched frames: begin_frame() / *_in_frame() / end_frame() or end_frame_async().await, over a GpuSurface render target (FrameBuffer, ExternalFrameBuffer, or your own type)
  • Persistent command list: 8 KiB circular CL (ST Resize_GPU pattern)
  • Error propagation: nema_get_error() and GPU2D SystemError
  • Cache coherency: I-cache invalidate + D-cache clean/invalidate around submissions, plus servicing NemaGFX's GPU-initiated cache-hold handshake on the error interrupt
  • Stroke APIs: draw_stroke_rect, draw_stroke_line_aa, draw_stroke_triangle_aa, etc.
  • Textured triangles: blit_tri_fit, blit_tri_uv

One-shot helpers such as clear(), fill_rect(), and blit() remain available; they submit immediately when no frame is open.

NemaGFX version

Bindings and prebuilt libraries are vendored by stm32-bindings, currently pinned to x-cube-image-processing v1.0.0 (NemaGFX v1.4.17). This crate never touches NemaGFX headers or .a files directly — everything comes through stm32-bindings' generated FFI.

License

This crate is MIT OR Apache-2.0, but NemaGFX itself is licensed separately under Think Silicon / ST terms with different redistribution conditions — review stm32-bindings' vendored license before publishing an application or crate that links the prebuilt NemaGFX library.


Overview (`embassy-stm32-wpan/README.md`)

embassy-stm32-wpan

Async WPAN (short range wireless) on STM32WB families.

Features

  • Rust interface to the WPAN stack running on the STM32WB co-processor .
  • bt-hci controller implementation, for use with the ST vendor commands
    and events of the stm32wb-hci crate.

stm32wb-hci only provides the commands and events of the BLE stack it runs on, selected with
wb-hci by one release and one stack profile:

  • STM32WB: the wireless binary flashed on CPU2, with one wb-fw-* feature (wb-fw-1-15-0 to
    wb-fw-1-24-0) and one wb-stack-* feature (wb-stack-full-extended, wb-stack-full,
    wb-stack-light, wb-stack-hci-layer-extended, wb-stack-hci-layer, wb-stack-hci-adv-scan).
    The BLE + Thread/Zigbee/MAC combo binaries carry the full BLE stack: use wb-stack-full.
  • STM32WBA: the STM32CubeWBA 1.10.0 library the bindings are generated from, with the profile of the
    ble-stack-* feature.
  • Embassy-net driver implementation for 802.15.4 MAC.

Examples

See the stm32wb examples.


Overview (`embassy-stm32/README.md`)

Embassy STM32 HAL

The embassy-stm32 HAL aims to provide a safe, idiomatic hardware abstraction layer for all STM32 families. The HAL implements both blocking and async APIs for many peripherals. Where appropriate, traits from both blocking and asynchronous versions of embedded-hal v0.2 and v1.0 are implemented, as well as serial traits from embedded-io[-async].

embassy-stm32 supports all STM32 chip families

STM32 microcontrollers come in many families and flavors, and supporting all of them is a big undertaking. Embassy takes advantage of the fact that the STM32 peripheral versions are shared across chip families. For example, instead of re-implementing the SPI peripheral for every STM32 chip family, embassy has a single SPI implementation that depends on code-generated register types that are identical for STM32 families with the same version of a given peripheral.

In practice, this works as follows:

  1. You tell the compiler which chip you’re using with a feature flag
  2. The stm32-metapac module generates register types for that chip at compile time, based on data from the stm32-data module
  3. The embassy-stm32 HAL picks the correct implementation each peripheral based on automatically-generated feature flags, and applies any other tweaks which are required for the HAL to work on that chip

Be aware that, while embassy-stm32 strives to consistently support all peripherals across all chips, this approach can lead to slightly different APIs and capabilities being available on different families. Check the documentation for the specific chip you’re using to confirm exactly what’s available.

Embedded-hal

The embassy-stm32 HAL implements the traits from embedded-hal (v0.2 and 1.0) and embedded-hal-async, as well as embedded-io and embedded-io-async.

`embassy-time` time driver

If a time-driver-* feature is enabled, embassy-stm32 provides a time driver for use with embassy-time. You can pick which hardware timer is used for this internally via the time-driver-tim* features, or let embassy pick with time-driver-any.

embassy-time has a default tick rate of 1MHz, which is fast enough to cause problems with the 16-bit timers currently supported by the embassy-stm32 time driver (specifically, if a critical section delays an IRQ by more than 32ms). To avoid this, it’s recommended to pick a lower tick rate. 32.768kHz is a reasonable default for many purposes.

When using the low-power feature and a timer that is not low-power capable to keep time, the precision of Duration may reduced to the RTC tick rate, which is most commmonly 256 Hz, if stop mode is entered between
when two Instant::now() calls are made. If higher precision is required, then a WakeGuard can be held to prevent the chip from entering stop or a timer that is low-power capable can be used. If the user does not
hold a WakeGuard, then embassy may enter low-power at any time depending on the internal implemenation of the low-power feature. HAL drivers should not be relied upon to block entering stop.

Interoperability

This crate can run on any executor.

Optionally, some features requiring embassy-time can be activated with the time feature. If you enable it,
you must link an embassy-time driver in your project.

The low-power feature integrates specifically with embassy-executor, it can't be used on other executors for now.


Overview (`embassy-sync/README.md`)

embassy-sync

An Embassy project.

Synchronization primitives and data structures with async support:

  • Channel - A Multiple Producer Multiple Consumer (MPMC) channel. Each message is only received by a single consumer.
  • PriorityChannel - A Multiple Producer Multiple Consumer (MPMC) channel. Each message is only received by a single consumer. Higher priority items are shifted to the front of the channel.
  • PubSubChannel - A broadcast channel (publish-subscribe) channel. Each message is received by all consumers.
  • Signal - Signalling latest value to a single consumer.
  • Watch - Signalling latest value to multiple consumers.
  • Mutex - Mutex for synchronizing state between asynchronous tasks.
  • Pipe - Byte stream implementing embedded_io traits.
  • WakerRegistration - Utility to register and wake a Waker.
  • AtomicWaker - Utility to register and wake a Waker from interrupt context.
  • MultiWakerRegistration - Utility registering and waking multiple Waker's.
  • LazyLock - A value which is initialized on the first access

Interoperability

Futures from this crate can run on any executor.


Overview (`embassy-time-driver/README.md`)

embassy-time-driver

This crate contains the driver trait necessary for adding embassy-time support
for a new hardware platform.

If you want to use embassy-time with already made drivers, you should depend on the main embassy-time crate, not on this crate.

If you are writing a driver, you should depend only on this crate, not on the main embassy-time crate.
This will allow your driver to continue working for newer embassy-time major versions, without needing an update,
if the driver trait has not had breaking changes.

How it works

embassy-time is backed by a global "time driver" specified at build time.
Only one driver can be active in a program.

All methods and structs transparently call into the active driver. This makes it
possible for libraries to use embassy-time in a driver-agnostic way without
requiring generic parameters.


Overview (`embassy-time-queue-utils/README.md`)

embassy-time-queue-utils

This crate contains timer queues to help implementing an embassy-time-driver.

As a HAL user, you should not need to depend on this crate.

As a HAL implementer, you need to depend on this crate if you want to implement a time driver,
but how you should do so is documented in embassy-time-driver.


Overview (`embassy-time/README.md`)

embassy-time

Timekeeping, delays and timeouts.

Timekeeping is done with elapsed time since system boot. Time is represented in
ticks, where the tick rate is defined either by the driver (in the case of a fixed-rate
tick) or chosen by the user with a tick rate feature. The chosen
tick rate applies to everything in embassy-time and thus determines the maximum
timing resolution of (1 / tick_rate) seconds.

Tick counts are 64 bits. The default tick rate of 1Mhz supports
representing time spans of up to ~584558 years, which is big enough for all practical
purposes and allows not having to worry about overflows.

Global time driver

The embassy-time crate is backed by a global "time driver" specified at build time.
Only one driver can be active in a program.

All methods and structs transparently call into the active driver. This makes it
possible for libraries to use embassy_time in a driver-agnostic way without
requiring generic parameters.

For more details, check the embassy_time_driver crate.

Instants and Durations

[Instant] represents a given instant of time (relative to system boot), and [Duration]
represents the duration of a span of time. They implement the math operations you'd expect,
like addition and substraction.

Delays and timeouts

[Timer] allows performing async delays. [Ticker] allows periodic delays without drifting over time.

An implementation of the embedded-hal delay traits is provided by [Delay], for compatibility
with libraries from the ecosystem.

Wall-clock time

The embassy-time crate deals exclusively with a monotonically increasing tick count.
Therefore it has no direct support for wall-clock time ("real life" datetimes
like 2021-08-24 13:33:21).

If persistence across reboots is not needed, support can be built on top of
embassy_time by storing the offset between "seconds elapsed since boot"
and "seconds since unix epoch".


Overview (`embassy-usb-dfu/README.md`)

embassy-usb-dfu

An implementation of the USB DFU 1.1 protocol using embassy-boot. It has 2 components depending on which feature is enabled by the user.

  • DFU protocol mode, enabled by the dfu feature. This mode corresponds to the transfer phase DFU protocol described by the USB IF. It supports DFU_DNLOAD requests if marked by the user, and will automatically reset the chip once a DFU transaction has been completed. It also responds to DFU_GETSTATUS, DFU_GETSTATE, DFU_ABORT, and DFU_CLRSTATUS with no user intervention.
  • DFU runtime mode, enabled by the application feature. This mode allows users to expose a DFU interface on their USB device, informing the host of the capability to DFU over USB, and allowing the host to reset the device into its bootloader to complete a DFU operation. Supports DFU_GETSTATUS and DFU_DETACH. When detach/reset is seen by the device as described by the standard, will write a new DFU magic number into the bootloader state in flash, and reset the system.

Verification

Embassy-boot provides functionality to verify that an update binary has been correctly signed using ed25519 as described in https://embassy.dev/book/#_verification. Even though the linked procedure describes the signature being concatenated to the end of the update binary, embassy-boot does not force this and is flexible in terms of how the signature for a binary is distributed. The current implementation in embassy-usb-dfu does however assume that the signature is 64 bytes long and concatenated to the end of the update binary since this is the simplest way to make it work with the usb-dfu mechanism. I.e. embassy-usb-dfu does not currently offer the same flexibility as embassy-boot.

To enable verification, you need to enable the verify feature.


Overview (`embassy-usb-driver/README.md`)

embassy-usb-driver

This crate contains the driver traits for embassy-usb. HAL/BSP crates can implement these
traits to add support for using embassy-usb for a given chip/platform.

The traits are kept in a separate crate so that breaking changes in the higher-level embassy-usb
APIs don't cause a semver-major bump of this crate. This allows existing HALs/BSPs to be used
with the newer embassy-usb without needing updates.

If you're writing an application using USB, you should depend on the main embassy-usb crate
instead of this one.

Interoperability

This crate can run on any executor.


Overview (`embassy-usb-logger/README.md`)

embassy-usb-logger

USB implementation of the log crate. This logger can be used by any device that implements embassy-usb. When running,
it will output all logging done through the log facade to the USB serial peripheral.

Usage

Add the following embassy task to your application. The Driver type is different depending on which HAL you use.

rust
#[embassy_executor::task]
async fn logger_task(driver: Driver<'static, USB>) {
   embassy_usb_logger::run!(1024, log::LevelFilter::Info, driver);
}

Overview (`embassy-usb-synopsys-otg/README.md`)

Embassy USB driver for the Synopsys USB OTG core

This crate implements embassy-usb-driver for Synopsys USB OTG devices.

It contains the "core" of the driver that is common across all chips using
the Synopsys OTG IP, but it doesn't contain chip-specific initialization such
as clock setup and GPIO muxing. You most likely don't want to use this crate
directly, but use it through a HAL that does the initialization for you.

List of HALs integrating this driver:

If you wish to integrate this crate into your device's HAL, you will need to add the
device-specific initialization. See the above crates for examples on how to do it.


Overview (`embassy-usb/README.md`)

embassy-usb

Async USB device and host stack for embedded devices in Rust.

Features

  • Native async.
  • Fully lock-free: endpoints are separate objects that can be used independently without needing a central mutex. If the driver supports it, they can even be used from different priority levels.
  • Suspend/resume, remote wakeup.
  • USB composite devices.
  • Ergonomic descriptor builder.
  • Ready-to-use implementations for a few USB classes (note you can still implement any class yourself outside the crate).
    • Serial ports (CDC ACM)
    • Ethernet (CDC NCM)
    • Human Interface Devices (HID)
    • MIDI
    • Generic USB Display (GUD)
    • Mass Storage (MSC)

The host module provides USB host enumeration,
descriptor parsing, and class drivers for devices including HID, CDC ACM, mass storage, MIDI, and USB Audio Class.

Adding support for new hardware

To add embassy-usb support for new hardware (i.e. a new MCU chip), you have to write a driver that implements
the embassy-usb-driver traits.

Before writing a new driver, you can first verify whether the chip uses a common USB IP. Several widely used USB IPs already have implementations available, such as:

  • Synopsys OTG (dwc2): Available at embassy-usb-synopsys-otg. This IP is used by vendors like STMicroelectronics, Espressif, and others.
  • Musbmhdrc (musb): Available at musb. This IP is used by vendors like TI, MediaTek, Puya, and others.

Driver crates should depend only on embassy-usb-driver, not on the main embassy-usb crate.
This allows existing drivers to continue working for newer embassy-usb major versions, without needing an update, if the driver
trait has not had breaking changes.

Configuration

embassy-usb has some configuration settings that are set at compile time, affecting sizes
and counts of buffers.

They can be set in two ways:

  • Via Cargo features: enable a feature like <name>-<value>. name must be in lowercase and
    use dashes instead of underscores. For example. max-interface-count-3. Only a selection of values
    is available, check Cargo.toml for the list.
  • Via environment variables at build time: set the variable named EMBASSY_USB_<value>. For example
    EMBASSY_USB_MAX_INTERFACE_COUNT=3 cargo build. You can also set them in the [env] section of .cargo/config.toml.
    Any value can be set, unlike with Cargo features.

Environment variables take precedence over Cargo features. If two Cargo features are enabled for the same setting
with different values, compilation fails.

`MAX_INTERFACE_COUNT`

Max amount of interfaces that can be created in one device. Default: 4.

Interoperability

This crate can run on any executor.


Overview (`examples/lpc55s69/README.md`)

LPC55S69 Examples

Available examples:

  • blinky_nop: Blink the integrated RED LED using nops as delay. Useful for flashing simple and known-good software on board.
  • button_executor: Turn on/off an LED by pressing the USER button. Demonstrates how to use the PINT and GPIO drivers.
  • blinky_embassy_time: Blink the integrated RED LED using embassy-time. Demonstrates how to use the time-driver that uses RTC.

Important Notes

On older version of probe-rs, some examples (such as blinky_embassy_time) do not work directly after flashing and the board must be reset after flashing. It is reccomended to update the version of probe-rs to the latest one.

When developing drivers for this board, probe-rs might not be able to flash the board after entering a fault. Either reset the board to clear the fault, or use NXP's proprietary software LinkServer/LinkFlash to bring the board back to a known-good state.


Overview (`examples/mimxrt6/README.md`)

embassy-imxrt-examples

Introduction

These examples illustrates how to use the embassy-imxrt HAL.

Adding Examples

Add uniquely named example to src/bin like adc.rs

Build

cd to examples folder
cargo build --bin <example_name> for example, cargo build --bin adc

Run

Assuming RT685 is powered and connected to Jlink debug probe and the latest probe-rs is installed via
$ cargo install probe-rs-tools --git https://github.com/probe-rs/probe-rs --locked
cd to examples folder
cargo run --bin <example_name> for example, cargo run --bin adc


Overview (`examples/mps3-an536/README.md`)

Examples for Cortex-R52 on MPS3-AN536 (in QEMU)

Run individual examples with:

sh
cargo run --bin <crate-name>

for example:

sh
cargo run --bin hello

Checklist before running examples

Before running these examples, you will need:

  • To have qemu-run on your PATH (try cargo install qemu-run)
  • To have qemu-system-arm, version 9 or higher, in your PATH

Overview (`examples/mspm0c1104/README.md`)

Examples for MSPM0C1104

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

A large number of the examples are written for the LP-MSPM0C1104 board.

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for C1104 it should be probe-rs run --chip MSPM0C1104. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-mspm0 feature. For the LP-MSPM0C1104 it should be mspm0c1104dgs20. Look in the Cargo.toml file of the embassy-mspm0 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/mspm0g3507/README.md`)

Examples for MSPM0M3507

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

A large number of the examples are written for the LP-MSPM0G3507 board.

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for G3507 it should be probe-rs run --chip MSPM0G3507. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-mspm0 feature. For the LP-MSPM0G3507 it should be mspm0g3507pm. Look in the Cargo.toml file of the embassy-mspm0 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/mspm0g3519/README.md`)

Examples for MSPM0G3519

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

A large number of the examples are written for the LP-MSPM0G3519 board.

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for G3519 it should be probe-rs run --chip MSPM0G3519. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-mspm0 feature. For the LP-MSPM0G3519 it should be mspm0g3519pz. Look in the Cargo.toml file of the embassy-mspm0 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/mspm0g5187/README.md`)

Examples for MSPM0G5187

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

A large number of the examples are written for the LP-MSPM0G5187 board.

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for G5187 it should be probe-rs run --chip MSPM0G5187. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-mspm0 feature. For the LP-MSPM0G3519 it should be mspm0g3519pz. Look in the Cargo.toml file of the embassy-mspm0 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/mspm0l1306/README.md`)

Examples for MSPM0L1306

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

A large number of the examples are written for the LP-MSPM0L1306 board.

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for L1306 it should be probe-rs run --chip MSPM0L1306. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-mspm0 feature. For the LP-MSPM0L1306 it should be mspm0l1306rhb. Look in the Cargo.toml file of the embassy-mspm0 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/mspm0l2228/README.md`)

Examples for MSPM0L2228

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

A large number of the examples are written for the LP-MSPM0L2228 board.

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for L2228 it should be probe-rs run --chip MSPM0L2228. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-mspm0 feature. For example for LP-MSPM0L2228 it should be mspm0l2228pn. Look in the Cargo.toml file of the embassy-mspm0 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/nrf54l15-app/README.md`)

nrf54l15-app examples

Examples for the application core of the nRF54L15.

sQSPI firmware blob license

The sqspi example uses the sQSPI soft peripheral, a QSPI/SPI controller
implemented in firmware that runs on the nRF54L15's FLPR coprocessor. The
firmware blob src/bin/sqspi_firmware.bin is redistributed from Nordic
Semiconductor's nRF Connect SDK (nrfxlib) and is not covered by embassy's
license:

text
Copyright (c) 2025 Nordic Semiconductor ASA

SPDX-License-Identifier: LicenseRef-Nordic-5-Clause

See the Nordic 5-Clause License
for the terms. All other files in this crate are licensed under embassy's usual
terms (MIT or Apache-2.0).


Overview (`examples/nrf54l15-flpr/README.md`)

nrf54l15-flpr examples

These examples must be used in combination with the corresponding app core example.

NOTE: The nightly rustc toolchain is required to support the riscv32emc target

To build

text
cargo +nightly build --release --bin blinky

When built, write the example to the expected location:

text
rust-objcopy -O ihex target/riscv32emc-unknown-none-elf/release/blinky blinky.hex
probe-rs download blinky.hex --binary-format hex --chip nRF54L15

Overview (`examples/qemu-virt-riscv64/README.md`)

Examples for RISC-V 64 (in QEMU `virt`)

These examples target a generic RV64IMAC core running on QEMU's virt
machine and exercise the platform-riscv64 thread executor.

Run individual examples with:

sh
cargo run --bin <crate-name>

for example:

sh
cargo run --bin hello

Expected output:

text
Hello from embassy-executor on RISC-V 64!
Hello from a spawned task!
Goodbye.

QEMU then exits with status 0 via the semihosting SYS_EXIT call.

Checklist before running examples

Before running these examples, you will need:

  • qemu-system-riscv64 on your PATH (typically packaged as qemu-system-misc
    on Debian/Ubuntu, qemu-system-riscv on Fedora/Arch, or qemu from Homebrew).

The runner is configured in .cargo/config.toml:

text
qemu-system-riscv64 -machine virt -cpu rv64 -semihosting -nographic -bios none -kernel <elf>

-bios none is important: it skips OpenSBI so the kernel ELF is loaded
directly at 0x80000000 (the start of RAM on the virt machine), which
matches memory.x.

Running manually

If cargo run does not pick up the runner for some reason, you can invoke
QEMU directly:

sh
cargo build --bin hello --release
qemu-system-riscv64 \
    -machine virt -cpu rv64 \
    -semihosting -nographic -bios none \
    -kernel target/riscv64imac-unknown-none-elf/release/hello

Press Ctrl-A X to terminate QEMU if a program hangs.

Verified QEMU CPU profiles

The example is verified end-to-end against the following qemu-system-riscv64 -cpu profiles. Run ./test-cpus.sh to reproduce — it builds the binary for
both Rust toolchain targets and asserts that stdout matches exactly and QEMU
exits with status 0 for every supported combination.

Toolchain target CPU profiles
riscv64imac-unknown-none-elf rv64, sifive-u54, sifive-e51, thead-c906, veyron-v1, max
riscv64gc-unknown-none-elf rv64, sifive-u54, thead-c906, veyron-v1, max

riscv64gc requires F+D extensions, so it is not run against sifive-e51
(which is RV64IMAC only). That binary will trap during riscv-rt's
floating-point initialisation on a core without F/D — it's an architectural
mismatch, not an executor bug.

The thead-c906 profile prints a benign QEMU-side warning about disabling
the Zfa extension; the program runs to completion regardless.


Overview (`examples/std/README.md`)

Running the `embassy-net` examples

To run net, tcp_accept, net_udp and net_dns examples you will need a tap interface. Before running these examples, create the tap99 interface. (The number was chosen to
hopefully not collide with anything.) You only need to do this once every time you reboot your computer.

sh
cd $EMBASSY_ROOT/examples/std/
sudo sh tap.sh

The example net_ppp requires different steps that are detailed in its section.

`net` example

For this example, you need to have something listening in the correct port. For example nc -lp 8000.

Then run the example located in the examples folder:

sh
cd $EMBASSY_ROOT/examples/std/
cargo run --bin net -- --tap tap99 --static-ip

`tcp_accept` example

This example listen for a tcp connection.

First run the example located in the examples folder:

sh
cd $EMBASSY_ROOT/examples/std/
cargo run --bin tcp_accept -- --tap tap99 --static-ip

Then open a connection to the port. For example nc 192.168.69.2 9999.

`net_udp` example

This example listen for a udp connection.

First run the example located in the examples folder:

sh
cd $EMBASSY_ROOT/examples/std/
cargo run --bin net_udp -- --tap tap99 --static-ip

Then open a connection to the port. For example nc -u 192.168.69.2 9400.

`net_dns` example

This example queries a DNS for the IP address of www.example.com.

In order to achieve this, the tap99 interface requires configuring tap99 as a gateway device temporarily.

For example, in Ubuntu you can do this by:

  1. Identifying your default route device. In the next example eth0
sh
ip r | grep "default"
default via 192.168.2.1 dev eth0 proto kernel metric 35
  1. Enabling temporarily IP Forwarding:
sh
sudo sysctl -w net.ipv4.ip_forward=1
  1. Configuring NAT to mascarade traffic from tap99 to eth0
sh
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i tap99 -j ACCEPT
sudo iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  1. Then you can run the example located in the examples folder:
sh
cd $EMBASSY_ROOT/examples/std/
cargo run --bin net_dns -- --tap tap99 --static-ip

`net_ppp` example

This example establish a Point-to-Point Protocol (PPP) connection that can be used, for example, for connecting to internet through a 4G modem via a serial channel.

The example creates a PPP bridge over a virtual serial channel between pty1 and pty2 for the example code and a PPP server running on the same computer.

To run this example you will need:

  • ppp (pppd server)
  • socat (socket CAT)

To run the examples you may follow the next steps:

  1. Save the PPP server configuration:
sh
sudo sh -c 'echo "myuser $(hostname) mypass 192.168.7.10" >> /etc/ppp/pap-secrets'
  1. Create a files pty1 and pty2 and link them
sh
cd $EMBASSY_ROOT/examples/std/
socat -v -x PTY,link=pty1,rawer PTY,link=pty2,rawer
  1. open a second terminal and start the PPP server:
sh
cd $EMBASSY_ROOT/examples/std/
sudo pppd $PWD/pty1 115200 192.168.7.1: ms-dns 8.8.4.4 ms-dns 8.8.8.8 nodetach debug local persist silent
  1. Open a third terminal and run the example
sh
cd $EMBASSY_ROOT/examples/std/
RUST_LOG=trace cargo run --bin net_ppp -- --device pty2
  1. Observe the output in the second and third terminal
  2. Open one last terminal to interact with net_ppp example through the PPP connection
sh
# ping the net_ppp client
ping 192.168.7.10
# open an tcp connection
nc 192.168.7.10 1234
# Type anything and observe the output in the different terminals

Overview (`examples/stm32f3/README.md`)

Examples for STM32F3 family

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for F303ZE it should be probe-rs run --chip STM32F303ZETx. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-stm32 feature. For example for F303ZE it should be stm32f303ze. Look in the Cargo.toml file of the embassy-stm32 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/stm32h745cm7/README.md`)

This example demonstrates how to use the display on the STM32H745I-DISCO board. It runs on the Cortex M7 core. It does not do anything with the CM4 core, so if you find that you have "weird" issues, disable the CM4 core using option byte BCM4=0 or just flash an empty loop onto it.

You can set the option byte using the following command:

sh
.\STM32_Programmer_CLI.exe -c port=SWD -ob BCM4=0 BCM7=1

The display code was adapted from the STM32H735 sample.

If you're interested in creating a multi-core application, please take a look at the stm32h755 examples (cm4 and cm7).


Overview (`examples/stm32l0/README.md`)

Examples for STM32L0 family

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for L073RZ it should be probe-rs run --chip STM32L073RZTx. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-stm32 feature. For example for L073RZ it should be stm32l073rz. Look in the Cargo.toml file of the embassy-stm32 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/stm32l4-rtic/README.md`)

Examples for STM32L4 family using Embassy with RTIC

Examples in this project demonstrates how to use Embassy with RTIC.

How to run examples

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for L4R5ZI-P it should be probe-rs run --chip STM32L4R5ZITxP. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-stm32 feature. For example for L4R5ZI-P it should be stm32l4r5zi. Look in the Cargo.toml file of the embassy-stm32 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/stm32l4/README.md`)

Examples for STM32L4 family

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for L4R5ZI-P it should be probe-rs run --chip STM32L4R5ZITxP. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-stm32 feature. For example for L4R5ZI-P it should be stm32l4r5zi. Look in the Cargo.toml file of the embassy-stm32 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/stm32l432/README.md`)

Examples for STM32L432 family

Examples in this repo should work with NUCLEO-L432KC board.

Run individual examples with

text
cargo run --bin <module-name>

for example

text
cargo run --bin blinky

Checklist before running examples

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for L432KCU6 it should be probe-rs run --chip STM32L432KCUx. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-stm32 feature. For example for L432KCU6 it should be stm32l432kc. Look in the Cargo.toml file of the embassy-stm32 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/stm32n6-flashboot/README.md`)

STM32N6 Flash Boot Example

Two-stage boot system (FSBL + application) for the STM32N6 using embassy-boot. Supports both the STM32N6570-DK and NUCLEO-N657X0-Q boards. The FSBL runs from SRAM, initializes external NOR flash in memory-mapped mode, and boots the application firmware with support for DFU updates.

Prerequisites

  • cargo-binutils: cargo install cargo-binutils
  • STM32CubeProgrammer (provides the signing tool)
  • probe-rs v0.32+ (not yet released — build from git master): cargo install probe-rs-tools --git https://github.com/probe-rs/probe-rs
  • just: cargo install just

Supported Boards

Board board value External Flash Size
STM32N6570-DK dk (default) MX66UW1G45G 128 MB
NUCLEO-N657X0-Q nucleo MX25UM51245G 64 MB

Set both BOOT switches to LOW for serial NOR boot (boot config 6, default when OTP is unfused).

Project Structure

Crate Description
fsbl/ First Stage Boot Loader — loaded by boot ROM into SRAM, enables debug access, configures clocks, initializes XSPI2 memory-mapped mode, then boots the app via embassy-boot
app/ Application firmware — runs from memory-mapped external flash at 0x70100400, with DFU update support (hold PE0 at reset for UART DFU, hold PE0 3s to confirm boot via mark_booted())

Quick Start

All recipes accept a board parameter (defaults to dk):

console
# DK (default)
just flash-all

# Nucleo
just board=nucleo flash-all

This builds both crates, converts to raw binaries, signs them for the boot ROM, flashes everything to external flash, and erases the boot state partition. After flashing, set BOOT switches to LOW and reset the board.

Run just --list to see all available recipes.

Memory Layout

text
External Flash (0x70000000, 128 MB):
  BOOTLOADER:  0x70000000 - 0x70100000 (1 MB)
  ACTIVE:      0x70100000 - 0x702FF000 (2044K)
  DFU:         0x70300000 - 0x70500000 (2048K)
  STATE:       0x70500000 - 0x70503000 (12K)

FSBL SRAM Layout:
  RAM:         0x34100000 - 0x34180400 (513K)
  FLASH:       0x34180400 - 0x341FF000 (507K)

Each signed image has a 0x400 header, so application code starts at ACTIVE + 0x400 = 0x70100400.

Key Recipes

Recipe Description
just build Build both FSBL and app
just flash-all Build, sign, flash everything, erase state
just flash-fsbl Build, sign, flash FSBL only
just flash-app Build, sign, flash app only
just test-dfu Flash app to DFU partition and trigger swap
just attach-fsbl Attach to running FSBL with defmt RTT output
just debug-fsbl Flash FSBL and attach for debugging
just erase-state Erase STATE partition (reset boot state)
just trigger-swap Write SWAP_MAGIC to trigger DFU swap on next boot
just uart-dfu Send firmware via XMODEM over UART (requires lrzsz)
just read-state Read STATE partition (debug)
just mark-booted Write BOOT_MAGIC to confirm boot from host
just clean Clean build artifacts

All recipes work with the board parameter, e.g. just board=nucleo flash-all.

Recipes prefixed with stm32- (e.g. just stm32-flash-all) use STM32_Programmer_CLI instead of probe-rs, as a fallback if probe-rs cannot flash external flash.

UART DFU

The application includes an XMODEM-CRC firmware receiver for cable-only DFU updates without a debug probe.

Pins: USART1 — PE5 (TX), PE6 (RX), 115200 baud, 8E1 (even parity)

Workflow:

  1. Build and sign the new firmware: just sign-app
  2. Start the XMODEM sender on the host first: just uart-dfu /dev/tty.usbmodemXXXX
  3. Reset the board while holding PE0 (tamper button) — the app enters DFU mode
  4. Firmware is received via XMODEM-CRC and written to the DFU partition
  5. After transfer completes, SWAP_MAGIC is written automatically — reset to boot new firmware

Requires lrzsz (sx command): brew install lrzsz (macOS) or apt install lrzsz (Linux).

Further Reading

For original boot flow notes and code snippets from the contributor who prototyped this approach, see BOOT_NOTES.md.


Overview (`examples/stm32n6/README.md`)

STM32N6 Examples

Simple standalone examples for the STM32N6570-DK and NUCLEO-N657X0-Q, primarily intended for dev mode — loaded directly to RAM via probe-rs with no flash boot required.

For a full two-stage boot system with firmware updates from external flash, see stm32n6-flashboot.

NeoChrom (NemaGFX)

The neochrom and neochrom_lcd examples use embassy-stm32-neochrom,
which pulls its NemaGFX bindings from stm32-bindings on crates.io — no local generation step needed.
See also ST's x-cube-image-processing
reference for the STM32N6570-DK.

CI builds use the default stub-gpu2d feature (link-only HAL stub, no hardware needed). Both examples
are hardware-validated on the STM32N6570-DK; for real GPU2D:

bash
cargo run --release --bin neochrom --no-default-features
cargo run --release --bin neochrom_lcd --no-default-features
cargo run --release --bin neochrom_graphics --no-default-features
  • neochrom — exercises fill, line, circle, and triangle APIs on a 64×64 RGBA8888 buffer.
  • neochrom_lcd — GPU-renders into double-buffered 800×480 RGB565 LTDC framebuffers in AXISRAM, driving the panel end-to-end.
  • neochrom_graphics — full 60 FPS dashboard: a embedded-3dgfx scene rasterized through the GPU2D, embedded-gui widgets, and a GPU-blitted text atlas. Runs at ~152 µs of GPU time per frame.

Neural-ART NPU

  • npu_mobilenet — real NPU bring-up. Runs an ST Edge AI compiled MobileNetV1-0.25
    network (single hardware epoch) through embassy_stm32::npu, on a fixed public-domain
    Mexican marigold input (npu-model/mexican_marigold_96x96.rgb). The trailing software
    epoch blocks (Softmax, Dequantize) that ST's compiler emits are reproduced with
    embedded-nn kernels, exposed as embassy_stm32::npu::epoch behind the npu-nn feature.
  • Full end-to-end inference (weights streamed from external flash, hardware NPU epoch, CPU
    softmax/dequantize/argmax) takes ~320 ms, ~150 ms of which is the NPU epoch itself. Two clock
    configs make that possible: PLL1 at 800 MHz CPU / 200 MHz system bus (same config as
    neochrom_lcd), and — the dominant factor by far — Octal DTR (8-line, double-transfer-rate)
    reads from the external NOR instead of a single-lane FASTREAD, matching ST's own
    stm32n6570_discovery_xspi.c bring-up. Without the Octal DTR switch this runs in ~9.6 s
    regardless of CPU/NPU clock, since streaming this model's ~7.9 MB of weights over a slow,
    single-lane, non-DTR link dominates everything else.
  • The compiled model classifies flowers (101 classes, likely Oxford 102 Flowers minus one
    unused class — see STAI_NETWORK_OUT_1_SIZE in Model/STM32N6570-DK/stai_network.h); the
    input is a flower so the logits actually carry signal. There's no golden-reference check
    against a host interpreter: the .tflite published alongside this compiled blob in ST's
    repo (Model/mobilenet_v1_0.25_96_tfs_int8.tflite) is a different, 5-class model (confirmed
    via embedded-nn-tflite: input [1,96,96,3] uint8, output [1,5] float32) — the repo ships
    two unversioned, mismatched models under the same demo, and no 101-class .tflite is
    published to validate against instead. See GOLDEN_LOGITS in npu_mobilenet.rs.

ST publishes the compiled model under SLA0044, so it is not vendored here. build.rs imports
it from a checkout of ST's public GettingStarted repository and the example is gated behind the
npu-model feature. Hardware-validated on the STM32N6570-DK; the Nucleo path is untested but
follows the same steps with board-nucleo swapped in throughout.

1. Get the model

bash
git clone --depth 1 https://github.com/STMicroelectronics/STM32N6-GettingStarted-ImageClassification
# Match the board dir to the feature you'll build with below (DK is the default feature).
export STM32N6_GETTINGSTARTED_MODEL_DIR=$PWD/STM32N6-GettingStarted-ImageClassification/Model/STM32N6570-DK

For the Nucleo, use Model/NUCLEO-N657X0-Q instead.

2. Program the model weights into external flash (one-time)

The example reads network weights from the board's external xSPI2 NOR at runtime — cargo run
only loads the firmware itself into RAM (dev mode), it does not program external flash. Do this
once per board, via STM32CubeProgrammer
(not the same tool as probe-rs/cargo run below — install it separately):

bash
# Adjust to your STM32CubeProgrammer install location.
CLI="<STM32CubeProgrammer_N6 Install Folder>/bin/STM32_Programmer_CLI"
DKEL="<STM32CubeProgrammer_N6 Install Folder>/bin/ExternalLoader/MX66UW1G45G_STM32N6570-DK.stldr"

"$CLI" -c port=SWD mode=HOTPLUG -el "$DKEL" -hardRst \
    -w "$STM32N6_GETTINGSTARTED_MODEL_DIR/network_data.hex"

For the Nucleo, use MX25UM51245G_STM32N6570-NUCLEO.stldr instead. This only needs redoing if
you erase/reflash that flash region or swap to a different model. If the erase/write fails with
Init function fail (the external loader itself never gets going), fully power-cycle the board
first — this chip's PMIC is sequenced by the boot ROM at power-on, and a -hardRst (NRST pulse)
alone doesn't redo that negotiation.

3. Build and run

bash
# Board defaults to the STM32N6570-DK; use --no-default-features --features npu-model,board-nucleo for the Nucleo.
cargo run --features npu-model --bin npu_mobilenet

The example verifies the weights were actually programmed (reading back a known value at
0x7038_0000) and prints a clear error instead of silently misbehaving if step 2 was skipped.
Expect it to end with something like:

text
NPU epoch complete in ~120_000_000 cycles (~150 ms at 800 MHz CPU clock)
NPU logits (i8): [...]
probabilities : [...]
=> class 55 (argmax i8 score 47), p(class) = 0.671875

(Exact logits/probabilities vary slightly run-to-run — quantization noise, not a bug — but the
winning class and its confidence stay consistent.)

The differences between the two boards (power supply topology, NOR size) are selected by the
board-dk / board-nucleo features.

Troubleshooting

  • Board must be in development mode (boot switches BOOT0/BOOT1 — see "Boot Modes" in
    ST's repo README, or Doc/Boot-Overview.md) — same requirement for cargo run's RAM load
    and for step 2's flash programming.
  • probe-rs reports SwdApFault, or a hard fault at reset with PC=0 before any log
    output
    : power-cycle the board (unplug/replug, don't just hit reset). This chip's debug port
    can get wedged after certain reset sequences and a real power-on-reset clears it.
  • probe-rs reports Target voltage (VAPP) is 0.00 V: the board itself isn't powered —
    check the power switch/cable, not the debug connection.
  • The firmware hangs during the octal DTR switch: ... log lines (no further output,
    probe-rs doesn't time out on its own): power-cycle the board. The flash's protocol-select
    bit (CR2 register 1) is volatile, so a power-cycle also resets it back to default SPI mode;
    a plain reset does not reliably do the same. This has been observed once, transiently, and
    ran cleanly on every attempt afterward — if it recurs consistently rather than clearing on
    power-cycle, that would point at a real bug in the mode-switch sequence
    (switch_flash_to_octal_dtr in npu_mobilenet.rs), not just a one-off.

Overview (`examples/stm32u5/README.md`)

STM32U5 Examples

Spi (blocking & DMA)

These examples use the BMP390 barometric pressure sensor, we send a read request to register 0x00 and we wait for the chip ID response (0x60).
The examples were tested on the nucleo_u545re_q board.

Please refer to the Figure 1 for the pin connections reference.

STM32 D10/PC_9 -> BMP390_CSB

STM32 D11/PA_7 -> BMP390_SDI

STM32 D12/PA_6 -> BMP390_SDO

STM32 D13/PA_5 -> BMP390_SCK


Overview (`examples/stm32wle5-lp/README.md`)

Low Power Examples for STM32WLEx family

Examples in this repo should work with LoRa-E5 Dev Board board.

Prerequsits

  • Connect a usb serial adapter to LPUart1 (this is where ALL logging will go)
  • Optional: Connect an amp meter that ran measure down to 0.1uA to the power test pins
  • cargo install defmt-print so you can print log messahes from LPUart1

Example Notes

All examples will set all pins to analog mode before configuring pins for the example, if any. This saves about 500uA!!!!

  • the adc example will sleep in STOP1 betwen samples and the chip will only draw about 13uA while sleeping
  • the blinky example will sleep in STOP2 and the chip will only draw 1uA or less while sleeping
  • the button_exti example will sleep in STOP2 and the chip will only draw 1uA or less while sleeping
  • the i2c examples will sleep in STOP1 between reads and the chip only draw about 10uA while sleeping

For each example you will need to start defmt-print with the example binary and the correct serial port in a seperate terminal. Example:

text
defmt-print -w -v -e target/thumbv7em-none-eabi/debug/<module-name> serial --path /dev/cu.usbserial-00000000 --baud 115200

Run individual examples with

text
cargo flash --chip STM32WLE5JCIx --connect-under-reset --bin <module-name>

for example

text
cargo flash --chip STM32WLE5JCIx --connect-under-reset --bin blinky

You can also run them with with run. However in this case expect probe-rs to be disconnected as soon as flashing is done as all IO pins are set to analog input!

text
cargo run --bin blinky

Checklist before running examples

You might need to adjust .cargo/config.toml, Cargo.toml and possibly update pin numbers or peripherals to match the specific MCU or board you are using.

  • Update .cargo/config.toml with the correct probe-rs command to use your specific MCU. For example for L432KCU6 it should be probe-rs run --chip STM32L432KCUx. (use probe-rs chip list to find your chip)
  • Update Cargo.toml to have the correct embassy-stm32 feature. For example for L432KCU6 it should be stm32l432kc. Look in the Cargo.toml file of the embassy-stm32 project to find the correct feature flag for your chip.
  • If your board has a special clock or power configuration, make sure that it is set up appropriately.
  • If your board has different pin mapping, update any pin numbers or peripherals in the given example code to match your schematic

If you are unsure, please drop by the Embassy Matrix chat for support, and let us know:

  • Which example you are trying to run
  • Which chip and board you are using

Embassy Chat: https://matrix.to/#/#embassy-rs:matrix.org


Overview (`examples/wasm/README.md`)

WASM example

Examples use a CLI tool named wasm-pack to build this example:

text
cargo install wasm-pack --version 0.12.1

Building

To build the example, run:

text
wasm-pack build --target web

Running

To run the example, start a webserver server the local folder:

text
python -m http.server

Then, open a browser at http://127.0.0.1:8000 and watch the ticker print entries to the window.


Overview (`tests/mcxa2xx/README.md`)

HIL setup

Implemented:

  • GPIO + interrupts
  • I2C controller + target
  • Uart
  • LPUART BBQueue continuous DMA RX
  • ADC
  • I3C
  • CRC
  • Watchdog
  • Flash
  • CTimer PWM
  • CTimer capture
  • LPTMR polling, async waits, cancellation, prescalers and FRO16K
  • LPTMR Embassy time backend (additional time-driver-lptmr build)
  • FREQME blocking/async one-shot and continuous internal clocks including SLOW_CLK, cancellation, IRQs and reconstruction (no wiring)
  • FREQME runtime scale/source/power reconfiguration and threshold-error recovery
  • SPI

Wiring:

  • I2C controller + target: LPI2C1 on arduino connector J4 to LPI2C2 on camera connector J9
    • SDA: P1_0 -> P1_8
    • SCL: P1_1 -> P1_9
  • Uart: LPUART3 on mikroBUS connector J5 to LPUART2 on arduino connector J1
    • P4_5 (TX) -> P2_3 (RX)
    • P4_2 (RX) -> P2_2 (TX)
  • ADC + GPIO + CTimer capture + CTimer PWM: ADC0_A1 on arduino connector J2 to CT_INP8 + CT0_MAT2 on arduino connector J2
    • P2_4 -> P1_8 (overlaps with I2C SDA but on different connector)
  • I3C: Only one peripheral, so no loopback tests. But it's connected to the P3T1755DP temperature sensor
  • SPI: LPSPI0 on mikroBUS connector J6 to LPSPI1 on arduino connector J2
    • CS: P1_3 -> P3_11
    • SCK: P1_1 -> P3_10 (overlaps with I2C SCL but on different connector)
    • MISO/SDI: P1_2 -> P3_9
    • MOSI/SDO: P1_0 -> P3_8

That's 9 wire connections in total.


Overview (`tests/rp/readme.md`)

Pico and Pico 2 Plus connections

GP0-GP1
GP3-GP4
GP6-GP9
GP7-GP11
GP18-GP20 with 10k pullup
GP19-GP21 with 10k pullup


Overview (`examples/ambiq/sparkfun-artemis/README.md`)

SparkFun Artemis (Apollo3) Examples

Examples for the Ambiq Apollo3, configured specifically for SparkFun Artemis boards.

Flashing & Bootloader

Artemis boards use the SparkFun SVL bootloader, which requires the application to boot from 0x10000.

  • Flashing: Simply run cargo run --release --bin <example_name>.
  • How it works: The .cargo/config.toml intercepts the runner and passes the binary to tools/flash.sh, which uses the SVL python script to flash over UART.

(Note: If you want to flash a bare chip at 0x0 using a standard SWD debugger and probe-rs, you must change memory.x's flash origin to 0x0 and remove the svl-vtor feature from Cargo.toml).

Examples

  • sync_blinky: Blocking blinky (no executor).
  • async_blinky: Demonstrates the Embassy executor and STIMER backend.
  • async_button: Using the Input driver's async .wait_for_falling_edge() to toggle an LED.

Overview (`examples/nrf9151/ns/README.md`)

You must flash the TFM before running any non-secure examples. The TFM
configures the secure and non-secure execution environments and then loads the
non-secure application. A reference TFM is included, and you can use the
provided helper script to flash it.


Overview (`examples/stm32n6/npu-model/README.md`)

NPU test assets

`mexican_marigold_96x96.rgb`

Raw RGB8, 96x96, 27 648 bytes — the fixed input tensor used by the
npu_mobilenet example. The compiled model under test is a MobileNetV1-0.25
flower classifier (101 classes — see GOLDEN_LOGITS in npu_mobilenet.rs
for why this differs from the 5-class .tflite ST publishes alongside it),
so a flower makes a meaningful in-distribution test input.

Source Wikimedia Commons, File:Mexican marigold.JPG
URL https://commons.wikimedia.org/wiki/Special:FilePath/Mexican_marigold.JPG?width=320
License Public domain (LicenseShortName: Public domain, License: pd)
Retrieved 2026-09-27
sha256 b9ac6a9ef04df8f01d05a5b7d17d0a8b3629a05b780bcde763787e4ffbd946e5

Conversion (330x247 JPEG -> raw RGB8, centre-cropped to square, then resized):

text
# decode + centre-crop to 330x330 + resize to 96x96 (triangle filter) -> raw RGB8

The Commons ImageDescription metadata field for this file is empty; the
subject is taken from the file title.

Why the raw form, and not a PNG

The ATON NPU block has no image decoder: the compiled network's input tensor
must already be uint8 NHWC in memory (1x96x96x3, scale 1/127.5,
zero-point 127), which is exactly what mexican_marigold_96x96.rgb holds. It
is embedded into the example with include_bytes!, so the bytes fed to the NPU
are byte-identical to the ones the reference was computed from.

Note that embedded-nn-tflite rewrites UINT8 tensors to INT8 by
subtracting 128 from values and zero-points, so the host interpreter is fed
pixel - 128. That is arithmetically the same computation
((v - 128) - (zp - 128) == v - zp), which is why the stored file stays raw
uint8.


Overview (`examples/stm32wb/firmware/README.md`)

STM32WB5x coprocessor binaries

fus_update embeds the ST-signed coprocessor binaries from the STM32CubeWB package
and installs them with the FUS (firmware upgrade services) at runtime — no
STM32CubeProgrammer needed.

Download them with either script (both are locked to a fixed STM32CubeWB
revision, so the example always embeds the same, known-good binaries):

sh
./download.sh        # Linux/macOS/Git Bash
./download.ps1       # Windows PowerShell

or manually from the
STM32CubeWB repository
(also mirrored in the STM32CubeWB MCU package and on st.com).

File Purpose
stm32wb5x_FUS_fw_for_fus_0_5_3.bin upgrades FUS V0.5.3 (factory default) to V1.2.0
stm32wb5x_FUS_fw_1_2_0.bin upgrades FUS V1.x (< V1.2.0) to V1.2.0
stm32wb5x_FUS_fw.bin upgrades FUS V1.2.0 to the latest FUS V2
stm32wb5x_BLE_Mac_802_15_4_fw.bin BLE + MAC 802.15.4 combo wireless stack
stm32wb5x_BLE_HCILayer_fw.bin BLE HCI layer (controller only, for an external host)

See the Release_Notes.html in the same repository directory for version details.


Overview (`examples/boot/application/nrf/README.md`)

Examples using bootloader

Example for nRF demonstrating the bootloader. The example consists of application binaries, 'a'
which allows you to press a button to start the DFU process, and 'b' which is the updated
application.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-nrf

Usage

text
# Use bare metal linker script
cp memory-bl.x ../../bootloader/nrf/memory.x

# Flash bootloader
cargo flash --manifest-path ../../bootloader/nrf/Cargo.toml --features embassy-nrf/nrf52840 --target thumbv7em-none-eabi --release --chip nRF52840_xxAA
# Build 'b'
cargo build --release --bin b --features embassy-nrf/nrf52840,embassy-nrf/time-driver-rtc1
# Generate binary for 'b'
cargo objcopy --release --bin b --features embassy-nrf/nrf52840,embassy-nrf/time-driver-rtc1 --target thumbv7em-none-eabi -- -O binary b.bin

Flash `a` (which includes b.bin)

text
cargo flash --release --bin a --features embassy-nrf/nrf52840 --target thumbv7em-none-eabi --chip nRF52840_xxAA

You should then see a solid LED. Pressing button 1 will cause the DFU to be loaded by the bootloader. Upon
successfully loading, you'll see the LED flash. After 5 seconds, because there is no petting of the watchdog,
you'll see the LED go solid again. This indicates that the bootloader has reverted the update.


Overview (`examples/boot/application/rp/README.md`)

Examples using bootloader

Example for Raspberry Pi Pico demonstrating the bootloader. The example consists of application binaries, 'a'
which waits for 5 seconds before flashing the 'b' binary, which blinks the LED.

NOTE: The 'b' binary does not mark the new binary as active, so if you reset the device, it will roll back to the 'a' binary before automatically updating it again.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-rp

Usage

text
# Flash bootloader
cargo flash --manifest-path ../../bootloader/rp/Cargo.toml --release --chip RP2040

# Build 'b'
cargo build --release --bin b

# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

# Flash `a` (which includes b.bin)
cargo flash --release --bin a --chip RP2040

Overview (`examples/boot/application/rp235x/README.md`)

Examples using bootloader

Example for Raspberry Pi Pico 2 demonstrating the bootloader. The example consists of application binaries, 'a'
which waits for 5 seconds before flashing the 'b' binary, which blinks the LED.

The 'b' binary marks the new binary (itself) as active, so the device will run the blinking program on every subsequent reset.
When 'b' boots the first time the blinking is fast, and every reset after that it wil be slower.

Prerequisites

  • cargo-binutils
  • cargo-flash

Usage

text
# Flash bootloader
cargo flash --manifest-path ../../bootloader/rp235x/Cargo.toml --release --chip RP235x

# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

# Flash `a` (which includes b.bin)
cargo flash --release --bin a --chip RP235x

Depending on how you flash you might have to reset the device after, then wait as the updating process does take a couple of seconds.

By default, Cargo.toml specifies the rp235xa variant, you may need to change that.


Overview (`examples/boot/application/stm32f3/README.md`)

Examples using bootloader

Example for STM32F3 demonstrating the bootloader. The example consists of application binaries, 'a'
which allows you to press a button to start the DFU process, and 'b' which is the updated
application.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-stm32

Usage

text
# Flash bootloader
cargo flash --manifest-path ../../bootloader/stm32/Cargo.toml --release --features embassy-stm32/stm32f303re --chip STM32F303RETx
# Build 'b'
cargo build --release --bin b
# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

Flash `a` (which includes b.bin)

text
cargo flash --release --bin a --chip STM32F303RETx

Overview (`examples/boot/application/stm32f7/README.md`)

Examples using bootloader

Example for STM32F7 demonstrating the bootloader. The example consists of application binaries, 'a'
which allows you to press a button to start the DFU process, and 'b' which is the updated
application.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-stm32

Usage

text
# Flash bootloader
./flash-boot.sh
# Build 'b'
cargo build --release --bin b
# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

Flash `a` (which includes b.bin)

text
cargo flash --release --bin a --chip STM32F767ZITx

Overview (`examples/boot/application/stm32h7/README.md`)

Examples using bootloader

Example for STM32H7 demonstrating the bootloader. The example consists of application binaries, 'a'
which allows you to press a button to start the DFU process, and 'b' which is the updated
application.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-stm32

Usage

text
# Flash bootloader
./flash-boot.sh
# Build 'b'
cargo build --release --bin b
# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

Flash `a` (which includes b.bin)

text
cargo flash --release --bin a --chip STM32H743ZITx

Overview (`examples/boot/application/stm32l0/README.md`)

Examples using bootloader

Example for STM32L0 demonstrating the bootloader. The example consists of application binaries, 'a'
which allows you to press a button to start the DFU process, and 'b' which is the updated
application.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-stm32

Usage

text
# Flash bootloader
cargo flash --manifest-path ../../bootloader/stm32/Cargo.toml --release --features embassy-stm32/stm32l072cz --chip STM32L072CZTx
# Build 'b'
cargo build --release --bin b
# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

Flash `a` (which includes b.bin)

text
cargo flash --release --bin a --chip STM32L072CZTx

Overview (`examples/boot/application/stm32l1/README.md`)

Examples using bootloader

Example for STM32L1 demonstrating the bootloader. The example consists of application binaries, 'a'
which allows you to press a button to start the DFU process, and 'b' which is the updated
application.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-stm32

Usage

text
# Flash bootloader
cargo flash --manifest-path ../../bootloader/stm32/Cargo.toml --release --features embassy-stm32/stm32l151cb-a --chip STM32L151CBxxA
# Build 'b'
cargo build --release --bin b
# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

Flash `a` (which includes b.bin)

text
cargo flash --release --bin a --chip STM32L151CBxxA

Overview (`examples/boot/application/stm32l4/README.md`)

Examples using bootloader

Example for STM32L4 demonstrating the bootloader. The example consists of application binaries, 'a'
which allows you to press a button to start the DFU process, and 'b' which is the updated
application.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-stm32

Usage

text
# Flash bootloader
cargo flash --manifest-path ../../bootloader/stm32/Cargo.toml --release --features embassy-stm32/stm32l475vg --chip STM32L475VG
# Build 'b'
cargo build --release --bin b
# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

Flash `a` (which includes b.bin)

text
cargo flash --release --bin a --chip STM32L475VG

Overview (`examples/boot/application/stm32wb-dfu/README.md`)

Examples using bootloader

Example for STM32WB demonstrating the USB DFU application.

Usage

text
cargo flash --release --chip STM32WB55RGVx

Overview (`examples/boot/application/stm32wba-dfu/README.md`)

Examples using bootloader

Example for STM32WBA demonstrating the USB DFU application.

Usage

text
cargo flash --release --chip STM32WBA65RI

Overview (`examples/boot/application/stm32wl/README.md`)

Examples using bootloader

Example for STM32WL demonstrating the bootloader. The example consists of application binaries, 'a'
which allows you to press a button to start the DFU process, and 'b' which is the updated
application.

Prerequisites

  • cargo-binutils
  • cargo-flash
  • embassy-boot-stm32

Usage

text
# Flash bootloader
cargo flash --manifest-path ../../bootloader/stm32/Cargo.toml --release --features embassy-stm32/stm32wl55jc-cm4 --chip STM32WLE5JCIx
# Build 'b'
cargo build --release --bin b
# Generate binary for 'b'
cargo objcopy --release --bin b -- -O binary b.bin

Flash `a` (which includes b.bin)

text
cargo flash --release --bin a --chip STM32WLE5JCIx

Overview (`examples/boot/bootloader/nrf/README.md`)

Bootloader for nRF

The bootloader uses embassy-boot to interact with the flash.

Usage

Flash the bootloader

text
cargo flash --features embassy-nrf/nrf52832 --release --chip nRF52832_xxAA

Overview (`examples/boot/bootloader/rp/README.md`)

Bootloader for RP2040

The bootloader uses embassy-boot to interact with the flash.

Usage

Flashing the bootloader

text
cargo flash --release --chip RP2040

To debug, use cargo run and enable the debug feature flag

rust
cargo run --release --features debug

Overview (`examples/boot/bootloader/rp235x/README.md`)

Bootloader for RP235x

The bootloader uses embassy-boot to interact with the flash.

Usage

Flashing the bootloader either with cargo run -r (see "runner" .cargo/config.toml), or:

text
cargo flash --release --chip RP235x

By default, Cargo.toml specifies the rp235xa variant, you may need to change that.


Overview (`examples/boot/bootloader/stm32-dual-bank/README.md`)

STM32 dual-bank flash Bootloader

Overview

This bootloader leverages embassy-boot to interact with the flash.
This example targets STM32 devices with dual-bank flash memory, with a primary focus on the STM32H747XI series.
Users must modify the memory.x configuration file to match with the memory layout of their specific STM32 device.

Additionally, this example can be extended to utilize external flash memory, such as QSPI, for storing partitions.

Memory Configuration

In this example's memory.x file, various symbols are defined to assist in effective memory management within the bootloader environment.
For dual-bank STM32 devices, it's crucial to assign these symbols correctly to their respective memory banks.

Symbol Definitions

The bootloader's state and active symbols are anchored to the flash origin of bank 1:

  • __bootloader_state_start and __bootloader_state_end
  • __bootloader_active_start and __bootloader_active_end

In contrast, the Device Firmware Upgrade (DFU) symbols are aligned with the DFU flash origin in bank 2:

  • __bootloader_dfu_start and __bootloader_dfu_end
rust
__bootloader_state_start = ORIGIN(BOOTLOADER_STATE) - ORIGIN(**FLASH**);
__bootloader_state_end = ORIGIN(BOOTLOADER_STATE) + LENGTH(BOOTLOADER_STATE) - ORIGIN(**FLASH**);

__bootloader_active_start = ORIGIN(ACTIVE) - ORIGIN(**FLASH**);
__bootloader_active_end = ORIGIN(ACTIVE) + LENGTH(ACTIVE) - ORIGIN(**FLASH**);

__bootloader_dfu_start = ORIGIN(DFU) - ORIGIN(**DFU**);
__bootloader_dfu_end = ORIGIN(DFU) + LENGTH(DFU) - ORIGIN(**DFU**);

Flashing the Bootloader

To flash the bootloader onto your STM32H747XI device, use the following command:

bash
cargo flash --features embassy-stm32/stm32h747xi-cm7 --release --chip STM32H747XIHx

Overview (`examples/boot/bootloader/stm32/README.md`)

Bootloader for STM32

The bootloader uses embassy-boot to interact with the flash.

Usage

Flash the bootloader

text
cargo flash --features embassy-stm32/stm32wl55jc-cm4 --release --chip STM32WLE5JCIx

Overview (`examples/boot/bootloader/stm32wb-dfu/README.md`)

Bootloader for STM32

This bootloader implementation uses embassy-boot and embassy-usb-dfu to manage firmware updates and interact with the flash memory on STM32WB55 devices.

Prerequisites

  • Rust toolchain with cargo installed
  • cargo-flash for flashing the bootloader
  • dfu-util for firmware updates
  • cargo-binutils for binary generation

Usage

1. Flash the Bootloader

First, flash the bootloader to your device:

text
cargo flash --features embassy-stm32/stm32wb55rg --release --chip STM32WB55RGVx

2. Build and Flash Application

Generate your application binary and flash it using DFU:

text
cargo objcopy --release -- -O binary fw.bin
dfu-util -d c0de:cafe -w -D fw.bin

3. Sign Updates Before Flashing (Optional)

Currently, embassy-usb-dfu only supports a limited implementation of the generic support for ed25519-based update verification in embassy-boot. This implementation assumes that a signature is simply concatenated to the end of an update binary. For more details, please see https://embassy.dev/book/#_verification and/or refer to the documentation for embassy-boot-dfu.

To sign (and then verify) application updates, you will first need to generate a key pair:

text
signify-openbsd -G -n -p secrets/key.pub -s secrets/key.sec
tail -n1 secrets/key.pub | base64 -d -i - | dd ibs=10 skip=1 > secrets/key.pub.short

Then you will need to sign all you binaries with the private key:

text
cargo objcopy --release -- -O binary fw.bin
shasum -a 512 -b fw.bin | head -c128 | xxd -p -r > target/fw-hash.txt
signify-openbsd -S -s secrets/key.sec -m target/fw-hash.txt -x target/fw-hash.sig
cp fw.bin fw-signed.bin
tail -n1 target/fw-hash.sig | base64 -d -i - | dd ibs=10 skip=1 >> fw-signed.bin
dfu-util -d c0de:cafe -w -D fw-signed.bin

Finally, as shown in this example with the verify feature flag enabled, you then need to embed the public key into your bootloader so that it can verify update signatures.

N.B. Please note that the exact steps above are NOT a good example of how to manage your keys securely. In a production environment, you should take great care to ensure that (at least the private key) is protected and not leaked into your version control system.

Troubleshooting

  • Make sure your device is in DFU mode before flashing
  • Verify the USB VID:PID matches your device (c0de:cafe)
  • Check USB connections if the device is not detected
  • Make sure the transfer size option of dfu-util matches the bootloader configuration. By default, dfu-util will use the transfer size reported by the device, but you can override it with the -t option if needed.
  • Make sure control_buf size is larger than or equal to the usb_dfu BLOCK_SIZE parameter (in this example, both are set to 4096 bytes).

Overview (`examples/boot/bootloader/stm32wba-dfu/README.md`)

Bootloader for STM32

This bootloader implementation uses embassy-boot and embassy-usb-dfu to manage firmware updates and interact with the flash memory on STM32WB55 devices.

Prerequisites

  • Rust toolchain with cargo installed
  • cargo-flash for flashing the bootloader
  • dfu-util for firmware updates
  • cargo-binutils for binary generation

Usage

1. Flash the Bootloader

First, flash the bootloader to your device:

text
cargo flash --features embassy-stm32/stm32wba65ri --release --chip STM32WBA65RI

2. Build and Flash Application

Generate your application binary and flash it using DFU:

text
cargo objcopy --release -- -O binary fw.bin
dfu-util -d c0de:cafe -w -D fw.bin

3. Sign Updates Before Flashing (Optional)

Currently, embassy-usb-dfu only supports a limited implementation of the generic support for ed25519-based update verfication in embassy-boot. This implementation assumes that a signature is simply concatenated to the end of an update binary. For more details, please see https://embassy.dev/book/#_verification and/or refer to the documentation for embassy-boot-dfu.

To sign (and then verify) application updates, you will first need to generate a key pair:

text
signify-openbsd -G -n -p secrets/key.pub -s secrets/key.sec
tail -n1 secrets/key.pub | base64 -d -i - | dd ibs=10 skip=1 > secrets/key.pub.short

Then you will need to sign all you binaries with the private key:

text
cargo objcopy --release -- -O binary fw.bin
shasum -a 512 -b fw.bin | head -c128 | xxd -p -r > target/fw-hash.txt
signify-openbsd -S -s secrets/key.sec -m target/fw-hash.txt -x target/fw-hash.sig
cp fw.bin fw-signed.bin
tail -n1 target/fw-hash.sig | base64 -d -i - | dd ibs=10 skip=1 >> fw-signed.bin
dfu-util -d c0de:cafe -w -D fw-signed.bin

Finally, as shown in this example with the verify feature flag enabled, you then need to embed the public key into your bootloader so that it can verify update signatures.

N.B. Please note that the exact steps above are NOT a good example of how to manage your keys securely. In a production environment, you should take great care to ensure that (at least the private key) is protected and not leaked into your version control system.

Troubleshooting

  • Make sure your device is in DFU mode before flashing
  • Verify the USB VID:PID matches your device (c0de:cafe)
  • Check USB connections if the device is not detected
  • Make sure the transfer size option of dfu-util matches the bootloader configuration. By default, dfu-util will use the transfer size reported by the device, but you can override it with the -t option if needed.
  • Make sure control_buf size is larger than or equal to the usb_dfu BLOCK_SIZE parameter (in this example, both are set to 4096 bytes).

Index (`docs/index.adoc`)

:description: Embassy Book
:sectanchors:
:doctype: book
:toc:
:toc-placement: left
:toclevels: 2
:imagesdir: images
:source-highlighter: rouge

Embassy Book

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

include::pages/overview.adoc[leveloffset = 1]
include::pages/beginners.adoc[leveloffset = 1]
include::pages/developer.adoc[leveloffset = 1]
include::pages/system.adoc[leveloffset = 1]
include::pages/faq.adoc[leveloffset = 1]


Pages Basic Application (`docs/pages/basic_application.adoc`)

= 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 link:https://github.com/embassy-rs/embassy/tree/main/docs/examples/basic[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).

[source,rust]

include::../examples/basic/src/main.rs[lines="1..2"]

=== 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:

[source,rust]

include::../examples/basic/src/main.rs[lines="9"]

=== Task declaration

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

[source,rust]

include::../examples/basic/src/main.rs[lines="12..23"]

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:

[source,rust]

include::../examples/basic/src/main.rs[lines="26..-1"]

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:

. Creates an Embassy Executor
. Defines a main task for the entry point
. 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:

[source,toml]

include::../examples/basic/Cargo.toml[lines="10..12"]

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.


Pages Beginners (`docs/pages/beginners.adoc`)

= 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.

include::getting_started.adoc[leveloffset = 2]
include::basic_application.adoc[leveloffset = 2]
include::project_structure.adoc[leveloffset = 2]
include::new_project.adoc[leveloffset = 2]
include::best_practices.adoc[leveloffset = 2]
include::layer_by_layer.adoc[leveloffset = 2]

== What's next?

Now that you're familiar with the basics, the xref:_system_description[System description] section covers the executor, HALs, bootloader, and other Embassy components in more detail.


Pages Best Practices (`docs/pages/best_practices.adoc`)

= Best Practices

Over time, a couple of best practices have emerged. The following list should serve as a guideline for developers writing embedded software in Rust, especially in the context of the Embassy framework.

== Passing Buffers by Reference
It may be tempting to pass arrays or wrappers, like link:https://docs.rs/heapless/latest/heapless/[`heapless::Vec`],
to a function or return one just like you would with a std::Vec. However, in most embedded applications you don't
want to spend resources on an allocator and end up placing buffers on the stack. This, however, can easily blow up
your stack if you are not careful.

Consider the following example: [,rust]

fn process_buffer(mut buf: [u8; 1024]) -> [u8; 1024] {
// do stuff and return new buffer
for elem in buf.iter_mut() {
*elem = 0;
}
buf
}

pub fn main() -> () {
let buf = [1u8; 1024];
let buf_new = process_buffer(buf);
// do stuff with buf_new
()

}

When calling process_buffer in your program, a copy of the buffer you pass to the function will be created,
consuming another 1024 bytes.
After the processing, another 1024 byte buffer will be placed on the stack to be returned to the caller.
(You can check the assembly, there will be two memcopy operations, e.g., bl __aeabi_memcpy when compiling for a Cortex-M processor.)

Possible Solution:

Pass the data by reference and not by value on both, the way in and the way out.
For example, you could return a slice of the input buffer as the output.
Requiring the lifetime of the input slice and the output slice to be the same, the memory safety of this procedure will be enforced by the compiler.

[,rust]

fn process_buffer<'a>(buf: &'a mut [u8]) -> &'a mut[u8] {
for elem in buf.iter_mut() {
*elem = 0;
}
buf
}

pub fn main() -> () {
let mut buf = [1u8; 1024];
let buf_new = process_buffer(&mut buf);
// do stuff with buf_new
()

}


Pages Bootloader (`docs/pages/bootloader.adoc`)

= Bootloader

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

The update method used is referred to as an A/B partition update scheme.

With a general-purpose OS, A/B partition update is accomplished by directly booting either the A or B partition depending on the update state.
To accomplish the same goal in a way that is portable across all microcontrollers, embassy-boot swaps data page by page (in both directions) between the DFU and the Active partition when a firmware update is triggered. +
Because the original Active application is moved into the DFU partition during this update, the operation can be reversed if the update is interrupted or the new firmware does not flag that it booted successfully. +
See the design section for more details on how this is implemented.

The bootloader can be used either as a library or be flashed directly if you are happy with the default configuration and capabilities.

By design, the bootloader does not provide any network capabilities. Networking capabilities for fetching new firmware can be provided by the user application, using the bootloader as a library for updating the firmware, or by using the bootloader as a library and adding this capability yourself.

The bootloader supports both internal and external flash by relying on the embedded-storage traits. The bootloader optionally supports the verification of firmware that has been digitally signed (recommended).

== Hardware support

The bootloader supports:

  • nRF52 with and without softdevice
  • STM32 L4, WB, WL, L1, L0, F3, F7 and H7
  • Raspberry Pi: RP2040, RP235x

In general, the bootloader works on any platform that implements the embedded-storage traits for its internal flash, but may require custom initialization code to work.

STM32L0x1 devices require the flash-erase-zero feature to be enabled.

== Design

image::bootloader_flash.png[Bootloader flash layout]

The bootloader divides the storage into 4 main partitions, configurable when creating the bootloader
instance or via linker scripts:

  • BOOTLOADER - Where the bootloader is placed. The bootloader itself consumes about 8kB of flash, but if you need to debug it and have space available, increasing this to 24kB will allow you to run the bootloader with probe-rs.
  • ACTIVE - Where the main application is placed. The bootloader will attempt to load the application at the start of this partition. This partition is only written to by the bootloader. The size required for this partition depends on the size of your application.
  • DFU - Where the application-to-be-swapped is placed. This partition is written to by the application. This partition must be at least 1 page bigger than the ACTIVE partition, since the swap algorithm uses the extra space to ensure power safe copy of data:

Partition Sizedfu= Partition Sizeactive+ Page Sizeactive
+
All values are specified in bytes.

  • BOOTLOADER STATE - Where the bootloader stores the current state describing if the active and dfu partitions need to be swapped. When the new firmware has been written to the DFU partition, a magic field is written to instruct the bootloader that the partitions should be swapped. This partition must be able to store a magic field as well as the partition swap progress. The partition size is given by:

Partition Sizestate = (2 × Write Sizestate) + (4 × Write Sizestate × Partition Sizeactive / Page Sizeactive)
+
All values are specified in bytes.

The partitions for ACTIVE (+BOOTLOADER), DFU and BOOTLOADER_STATE may be placed in separate flash. The page size used by the bootloader is determined by the lowest common multiple of the ACTIVE and DFU page sizes.
The BOOTLOADER_STATE partition must be big enough to store two words, plus four words per page in the ACTIVE partition.

The bootloader has a platform-agnostic part, which implements the power fail safe swapping algorithm given the boundaries set by the partitions. The platform-specific part is a minimal shim that provides additional functionality such as watchdogs or supporting the nRF52 softdevice.

NOTE: The linker scripts for the application and bootloader look similar, but the FLASH region must point to the BOOTLOADER partition for the bootloader, and the ACTIVE partition for the application.

=== FirmwareUpdater

The FirmwareUpdater is an object for conveniently flashing firmware to the DFU partition and subsequently marking it as being ready for swapping with the active partition on the next reset. Its principle methods are write_firmware, which is called once per the size of the flash "write block" (typically 4KiB), and mark_updated, which is the final call.

=== Verification

The bootloader supports the verification of firmware that has been flashed to the DFU partition. Verification requires that firmware has been signed digitally using a signature algorithm provided by embassy_crypto. With verification enabled, the FirmwareUpdater::verify_and_mark_updated method is called in place of mark_updated. A public key and signature are required, along with the actual length of the firmware that has been flashed. If verification fails then the firmware will not be marked as updated and therefore be rejected.

Signatures are normally conveyed with the firmware to be updated and not written to flash. How signatures are provided is a firmware responsibility.

==== Tips on keys and signing with ed25519

Ed25519 is a public key signature system where you are responsible for keeping the private key secure. We recommend embedding the public key in your program so that it can be easily passed to verify_and_mark_updated. An example declaration of the public key in your firmware:

[source, rust]

static PUBLIC_SIGNING_KEY: &[u8] = include_bytes!("key.pub");

Signatures are often conveyed along with firmware by appending them.

Ed25519 keys can be generated by a variety of tools. We recommend link:https://man.openbsd.org/signify[`signify`] as it is in wide use to sign and verify OpenBSD distributions, and is straightforward to use.

The following set of Bash commands can be used to generate public and private keys on Unix platforms, and also generate a local key.pub file with the signify file headers removed. Declare a SECRETS_DIR environment variable in a secure location.

[source, bash]

signify -G -n -p $SECRETS_DIR/key.pub -s $SECRETS_DIR/key.sec tail -n1 $SECRETS_DIR/key.pub | base64 -d -i - | dd ibs=10 skip=1 > key.pub chmod 700 $SECRETS_DIR/key.sec export SECRET_SIGNING_KEY=$(tail -n1 $SECRETS_DIR/key.sec)

Then, to sign your firmware given a declaration of FIRMWARE_DIR and a firmware filename of myfirmware:

[source, bash]

shasum -a 512 -b $FIRMWARE_DIR/myfirmware | head -c128 | xxd -p -r > $SECRETS_DIR/message.txt signify -S -s $SECRETS_DIR/key.sec -m $SECRETS_DIR/message.txt -x $SECRETS_DIR/message.txt.sig cp $FIRMWARE_DIR/myfirmware $FIRMWARE_DIR/myfirmware+signed tail -n1 $SECRETS_DIR/message.txt.sig | base64 -d -i - | dd ibs=10 skip=1 >> $FIRMWARE_DIR/myfirmware+signed

Remember, guard the $SECRETS_DIR/key.sec key as compromising it means that another party can sign your firmware.


Pages Developer (`docs/pages/developer.adoc`)

= For developers

This section covers the internals of Embassy, aimed at contributors and developers who want to understand how Embassy is built or add support for new hardware.

include::developer_stm32.adoc[leveloffset = 2]


Pages Developer Stm32 (`docs/pages/developer_stm32.adoc`)

= STM32

== Understanding metapac

When a project that imports embassy-stm32 is compiled, that project selects the feature corresponding to the chip that project is using. Based on that feature, embassy-stm32 selects supported link:https://anysilicon.com/ip-intellectual-property-core-semiconductors/[IP] for the chip, and enables the corresponding HAL implementations. But how does embassy-stm32 know what IP the chip contains, out of the hundreds of chips that we support? It's a long story that starts with stm32-data-sources.

== stm32-data-sources

link:https://github.com/embassy-rs/stm32-data-sources[`stm32-data-sources`] is a mostly barren repository. It has no README, no documentation, and few watchers. But it's the core of what makes embassy-stm32 possible. The data for every chip that we support is taken in part from a corresponding XML file like link:https://github.com/embassy-rs/stm32-data-sources/blob/b8b85202e22a954d6c59d4a43d9795d34cff05cf/cubedb/mcu/STM32F051K4Ux.xml[`STM32F051K4Ux.xml`]. In that file, you'll see lines like the following:

[source,xml]


These lines indicate that this chip has an i2c, and that it's version is "v1_1". It also indicates that it has a general purpose timer that with a version of "v2_x". From this data, it's possible to determine which implementations should be included in embassy-stm32. But actually doing that is another matter.

== stm32-data

While all users of this project are familiar with embassy-stm32, fewer are familiar with the project that powers it: stm32-data. This project doesn't just aim to generate data for embassy-stm32, but for machine consumption in general. To achieve this, information from multiple files from the stm32-data-sources project are combined and parsed to assign register block implementations for each supported IP. The core of this matching resides in chips.rs:

[source,rust]

text
(".*:I2C:i2c2_v1_1", ("i2c", "v2", "I2C")),
// snip
(r".*TIM\d.*:gptimer.*", ("timer", "v1", "TIM_GP16")),

In this case, the i2c version corresponds to our "v2" and the general purpose timer version corresponds to our "v1". Therefore, the i2c_v2.yaml and timer_v1.yaml register block implementations are assigned to those IP, respectively. The result is that these lines are generated in STM32F051K4.json:

[source,json]

text
{
    "name": "I2C1",
    "address": 1073763328,
    "registers": {
        "kind": "i2c",
        "version": "v2",
        "block": "I2C"
    },
    // snip
}
// snip
{
    "name": "TIM1",
    "address": 1073818624,
    "registers": {
        "kind": "timer",
        "version": "v1",
        "block": "TIM_ADV"
    },
    // snip
}

In addition to register blocks, data for pin and RCC mapping is also generated and consumed by embassy-stm32. stm32-metapac-gen is used to package and publish the data as a crate.

== embassy-stm32

In the lib.rs file located in the root of embassy-stm32, you'll see this line:

[source,rust]

#[cfg(i2c)] pub mod i2c;

And in the mod.rs of the i2c mod, you'll see this:

[source,rust]

#[cfg_attr(i2c_v2, path = "v2.rs")]

Because i2c is supported for STM32F051K4 and its version corresponds to our "v2", the i2c and i2c_v2, configuration directives will be present, and embassy-stm32 will include these files, respectively. This and other configuration directives and tables are generated from the data for chip, allowing embassy-stm32 to expressively and clearly adapt logic and implementations to what is required for each chip. Compared to other projects across the embedded ecosystem, embassy-stm32 is the only project that can re-use code across the entire stm32 lineup and remove difficult-to-implement unsafe logic to the HAL.


Pages Embassy In The Wild (`docs/pages/embassy_in_the_wild.adoc`)

= Embassy in the wild!

Here are known examples of real-world projects which make use of Embassy. Feel free to link:https://github.com/embassy-rs/embassy/blob/main/docs/pages/embassy_in_the_wild.adoc[add more]!

newer entries at the top


Pages Examples (`docs/pages/examples.adoc`)

= Examples

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

Main loop example

[source,rust]

include::../examples/examples/std/src/bin/tick.rs[]


Pages Faq (`docs/pages/faq.adoc`)

= Frequently Asked Questions

These are a list of unsorted, commonly asked questions and answers.

Please feel free to add items to link:https://github.com/embassy-rs/embassy/edit/main/docs/pages/faq.adoc[this page], especially if someone in the chat answered a question for you!

== How to deploy to RP2040 or RP235x without a debugging probe.

Install link:https://github.com/raspberrypi/pico-sdk-tools/releases[Picotool] for uploading the binary.

Configure the runner to use this tool, add this to `.cargo/config.toml`: [source,toml]

[target.'cfg(all(target_arch = "arm", target_os = "none"))'] runner = "picotool load --update --verify --execute -t elf"

Picotool will detect your device and upload the binary, skipping identical flash sectors (the --update command-line flag), verify that the binary was written correctly (--verify), and then run your new code (--execute). Run picotool help load for more information.

== Missing main macro

If you see an error like this:

[source,rust]

#[embassy_executor::main] | ^^^^ could not find `main` in `embassy_executor`

You are likely missing some features of the embassy-executor crate.

For Cortex-M targets, check whether ALL of the following features are enabled in your Cargo.toml for the embassy-executor crate:

  • arch-cortex-m
  • executor-thread

For ESP32, consider using the executors and #[main] macro provided by link:https://crates.io/crates/esp-hal[esp-hal].

== Why is my binary so big?

The first step to managing your binary size is to set up your link:https://doc.rust-lang.org/cargo/reference/profiles.html[profiles].

[source,toml]

[profile.release]
lto = true
opt-level = "s"
incremental = false
codegen-units = 1

note: debug = true is okay - debuginfo isn't flashed to the device!

debug = true

All of these flags are elaborated on in the Rust Book page linked above.

=== My binary is still big... filled with std::fmt stuff!

This means your code is sufficiently complex that panic! invocation's formatting requirements could not be optimized out, despite your usage of panic-halt or panic-reset.

You can remedy this by adding the following to your .cargo/config.toml:

[source,toml]

[unstable] build-std = ["core"] build-std-features = ["panic_immediate_abort"]

This replaces all panics with a UDF (undefined) instruction.

Depending on your chipset, this will exhibit different behavior.

Refer to the spec for your chipset, but for thumbv6m, it results in a hardfault. Which can be configured like so:

[source,rust]

#[exception]
unsafe fn HardFault(_frame: &ExceptionFrame) -> ! {
SCB::sys_reset() // <- you could do something other than reset

}

Refer to cortex-m's link:https://docs.rs/cortex-m-rt/latest/cortex_m_rt/attr.exception.html[exception handling] for more info.

== embassy-time throws linker errors

If you see linker error like this:

[source,text]

= note: rust-lld: error: undefined symbol: _embassy_time_now
>>> referenced by driver.rs:127 (src/driver.rs:127)
>>> embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::now::hefb1f99d6e069842) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib

text
rust-lld: error: undefined symbol: _embassy_time_schedule_wake
      >>> referenced by driver.rs:144 (src/driver.rs:144)
      >>>               embassy_time-846f66f1620ad42c.embassy_time.4f6a638abb75dd4c-cgu.0.rcgu.o:(embassy_time::driver::schedule_wake::h530a5b1f444a6d5b) in archive Devel/Embedded/pogodyna/target/thumbv7em-none-eabihf/debug/deps/libembassy_time-846f66f1620ad42c.rlib

You probably need to enable a time driver for your HAL (not in embassy-time!). For example with embassy-stm32, you might need to enable time-driver-any:

[source,toml]

[dependencies.embassy-stm32]
version = "0.1.0"
features = [
# ...
"time-driver-any", # Add this line!
# ...

]

If you are in the early project setup phase and not using anything from the HAL, make sure the HAL is explicitly used to prevent the linker removing it as dead code by adding this line to your source:

[source,rust]

use embassy_stm32 as _;

Another common error you may experience is:

[source,text]

= note: rust-lld: error: undefined symbol: __pender
>>> referenced by mod.rs:373 (src/raw/mod.rs:373)
>>> embassy_executor-e78174e249bca7f4.embassy_executor.1e9d60fc90940543-cgu.0.rcgu.o:(embassy_executor::raw::Pender::pend::h0f19b6e01762e4cd) in archive [...]libembassy_executor-e78174e249bca7f4.rlib


There are two possible causes to this error:

  • You are using embassy-executor without enabling one of the architecture-specific features, but you are using a HAL that does not bring its own executors. For example, for Cortex-M (like the RP2040), you need to enable the arch-cortex-m feature of embassy-executor.
  • You are not using embassy-executor. In this case, you need to enable the one of the generic-queue-X features of embassy-time.

== Error: Only one package in the dependency graph may specify the same links value.

You have multiple versions of the same crate in your dependency tree. This means that some of your
embassy crates are coming from crates.io, and some from git, each of them pulling in a different set
of dependencies.

To resolve this issue, make sure to only use a single source for all your embassy crates!
To do this, you should patch your dependencies to use git sources using [patch.crates.io]
and maybe [patch.'https://github.com/embassy-rs/embassy.git'].

Example:

[source,toml]

[patch.crates-io]
embassy-time-queue-utils = { git = "https://github.com/embassy-rs/embassy.git", rev = "7f8af8a" }
embassy-time-driver = { git = "https://github.com/embassy-rs/embassy.git", rev = "7f8af8a" }

embassy-time = { git = "https://github.com/embassy-rs/embassy.git", rev = "7f8af8a" }


Note that the git revision should match any other embassy patches or git dependencies that you are using!

== How can I optimize the speed of my embassy-stm32 program?

== Can I use manual ISRs alongside Embassy?

Yes! This can be useful if you need to respond to an event as fast as possible, and the latency caused by the usual “ISR, wake, return from ISR, context switch to woken task” flow is too much for your application.

You may simply define a #[interrupt] fn INTERRUPT_NAME() {} handler as you would link:https://docs.rust-embedded.org/book/start/interrupts.html[in any other embedded rust project].

Or you may define a struct implementing the embassy-[family]::interrupt::typelevel::Handler trait with an on_interrupt() method, and bind it to the interrupt vector via the bind_interrupts! macro, which introduces only a single indirection. This allows the mixing of manual ISRs with Embassy driver-defined ISRs; handlers will be called directly in the order they appear in the macro.

== How can I measure resource usage (CPU, RAM, etc.)?

=== For CPU Usage:

There are a couple techniques that have been documented, generally you want to measure how long you are spending in the idle or low priority loop.

We need to document specifically how to do this in embassy, but link:https://blog.japaric.io/cpu-monitor/[this older post] describes the general process.

If you end up doing this, please update this section with more specific examples!

=== For Static Memory Usage

Tools like cargo size and cargo nm from cargo-binutils can tell you the size of any globals or other static usage. Specifically you will want to see the size of the .data and .bss sections, which together make up the total global/static memory usage.

=== For Max Stack Usage

Check out link:https://github.com/Dirbaio/cargo-call-stack/[`cargo-call-stack`] for statically calculating worst-case stack usage. There are some caveats and inaccuracies possible with this, but this is a good way to get the general idea. See link:https://github.com/dirbaio/cargo-call-stack#known-limitations[the README] for more details.

== The memory definition for my STM chip seems wrong, how do I define a memory.x file?

It could happen that your project compiles, flashes but fails to run. The following situation can be true for your setup:

The memory.x is generated automatically when enabling the memory-x feature on the embassy-stm32 crate in the Cargo.toml file.
This, in turn, uses stm32-metapac to generate the memory.x file for you. Unfortunately, more often than not this memory definition is not correct.

You can override this by adding your own memory.x file. Such a file could look like this:

text
MEMORY
{
  FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K
  RAM (xrw)  : ORIGIN = 0x20000000, LENGTH = 320K
}

_stack_start = ORIGIN(RAM) + LENGTH(RAM);

Please refer to the STM32 documentation for the specific values suitable for your board and setup. The STM32 Cube examples often contain a linker script .ld file.
Look for the MEMORY section and try to determine the FLASH and RAM sizes and section start.

If you find a case where the memory.x is wrong, please report it on link:https://github.com/embassy-rs/stm32-data/issues/301[this Github issue] so other users are not caught by surprise.

== The USB examples are not working on my board, is there anything else I need to configure?

If you are trying out the USB examples and your device does not connect, the most common issues are listed below.

=== Incorrect RCC config

Check your board and crystal/oscillator, in particular make sure that HSE is set to the correct value, e.g. 8_000_000 Hertz if your board does indeed run on a 8 MHz oscillator.

=== VBUS detection on STM32 platform

The USB specification requires that all USB devices monitor the bus for detection of plugging/unplugging actions. The devices must pull-up the D+ or D- lane as soon as the host supplies VBUS.

See the docs, for example at link:https://docs.embassy.dev/embassy-stm32/git/stm32f401vc/usb/struct.Config.html[`usb/struct.Config.html`] for information on how to enable/disable vbus_detection.

When the device is powered only from the USB bus that simultaneously serves as the data connection, this is optional. (If there's no power in VBUS the device would be off anyway, so it's safe to always assume there's power in VBUS, i.e. the USB cable is always plugged in). If your device doesn't have the required connections in place to allow VBUS sensing (see below), then this option needs to be set to false to work.

When the device is powered from another power source and therefore can stay powered through USB cable plug/unplug events, then this must be implemented and vbus_detection MUST be set to true.

If your board is powered from the USB and you are unsure whether it supports vbus_detection, consult the schematics of your board to see if VBUS is connected to PA9 for USB Full Speed or PB13 for USB High Speed, vice versa, possibly with a voltage divider. When designing your own hardware, see ST application note AN4879 (in particular section 2.6) and the reference manual of your specific chip for more details.

== Known issues (details and/or mitigations)

These are issues that are commonly reported. Help wanted fixing them, or improving the UX when possible!

=== STM32H5 and STM32H7 power issues

STM32 chips with built-in power management (SMPS and LDO) settings often cause user problems when the configuration does not match how the board was designed.

Settings from the examples, or even from other working boards, may not work on YOUR board, because they are wired differently.

Additionally, some PWR settings require a full device reboot (and enough time to discharge any power capacitors!), making this hard to troubleshoot. Also, some
"wrong" power settings will ALMOST work, meaning it will sometimes work on some boots, or for a while, but crash unexpectedly.

There is not a fix for this yet, as it is board/hardware dependant. See link:https://github.com/embassy-rs/embassy/issues/2806[this tracking issue] for more details

=== STM32 BDMA only working out of some RAM regions

The STM32 BDMA controller included in some STM32H7 chips has to be configured to use only certain regions of RAM,
otherwise the transfer will fail.

If you see errors that look like this:

[source,plain]

DMA: error on BDMA@1234ABCD channel 4

You need to set up your linker script to define a special region for this area and copy data to that region before using with BDMA.

General steps:

  1. Find out which memory region BDMA has access to. You can get this information from the bus matrix and the memory mapping table in the STM32 datasheet.
  2. Add the memory region to memory.x, you can modify the generated one from https://github.com/embassy-rs/stm32-data-generated/tree/main/data/chips.
  3. You might need to modify build.rs to make cargo pick up the modified memory.x.
  4. In your code, access the defined memory region using #[unsafe(link_section = ".xxx")]
  5. Copy data to that region before using BDMA.

See link:https://github.com/embassy-rs/embassy/blob/main/examples/stm32h7/src/bin/spi_bdma.rs[SMT32H7 SPI BDMA example] for more details.

== How do I switch to the main branch?

Sometimes to test new changes or fixes, you'll want to switch your project to using a version from GitHub.

You can add a section to your Cargo.toml file like this, you'll need to patch ALL embassy crates to the same revision:

Using patch will replace all direct AND indirect dependencies.

See the link:https://embassy.dev/book/#_starting_a_new_project[new project docs] for more details on this approach.

[source,toml]

[patch.crates-io]

make sure to get the latest git rev from github, you can see the latest one here:

https://github.com/embassy-rs/embassy/commits/main/

embassy-embedded-hal = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } embassy-rp = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } embassy-sync = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } embassy-time = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } embassy-usb = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" } embassy-usb-driver = { git = "https://github.com/embassy-rs/embassy", rev = "4cade64ebd34bf93458f17cfe85c5f710d0ff13c" }

== How do I add support for a new microcontroller to embassy?

This is particularly for cortex-m, and potentially risc-v, where there is already support for basics like interrupt handling, or even already embassy-executor support for your architecture.

This is a much harder path than just using Embassy on an already supported chip. If you are a beginner, consider using embassy on an existing, well supported chip for a while, before you decide to write drivers from scratch. It's also worth reading the existing source of supported Embassy HALs, to get a feel for how drivers are implemented for various chips. You should already be comfortable reading and writing unsafe code, and understanding the responsibilities of writing safe abstractions for users of your HAL.

This is not the only possible approach, but if you are looking for where to start, this is a reasonable way to tackle the task:

  1. First, drop by the Matrix room or search around to see if someone has already started writing drivers, either in Embassy or otherwise in Rust. You might not have to start from scratch!
  2. Make sure the target is supported in probe-rs, it likely is, and if not, there is likely a cmsis-pack you can use to add support so that flashing and debugging is possible. You will definitely appreciate being able to debug with SWD or JTAG when writing drivers!
  3. See if there is an SVD (or SVDs, if it's a family) available, if it is, run it through chiptool to create a PAC for low level register access. If not, there are other ways (like scraping the PDF datasheets or existing C header files), but these are more work than starting from the SVD file to define peripheral memory locations necessary for writing drivers.
  4. Either make a fork of embassy repo, and add your target there, or make a repo that just contains the PAC and an empty HAL. It doesn't necessarily have to live in the embassy repo at first.
  5. Get a hello world binary working on your chip, either with minimal HAL or just PAC access, use delays and blink a light or send some raw data on some interface, make sure it works and you can flash, debug with defmt + RTT, write a proper linker script, etc.
  6. Get basic timer operations and timer interrupts working, upgrade your blinking application to use hardware timers and interrupts, and ensure they are accurate (with a logic analyzer or oscilloscope, if possible).
  7. Implement the embassy-time driver API with your timer and timer interrupt code, so that you can use embassy-time operations in your drivers and applications.
  8. Then start implementing whatever peripherals you need, like GPIOs, UART, SPI, I2C, etc. This is the largest part of the work, and will likely continue for a while! Don't feel like you need 100% coverage of all peripherals at first, this is likely to be an ongoing process over time.
  9. Start implementing the embedded-hal, embedded-io, and embedded-hal-async traits on top of your HAL drivers, once you start having more features completed. This will allow users to use standard external device drivers (e.g. sensors, actuators, displays, etc.) with your HAL.
  10. Discuss upstreaming the PAC/HAL for embassy support, or make sure your drivers are added to the awesome-embedded-rust list so that people can find it.

== Multiple Tasks, or one task with multiple futures?

Some examples end like this in main:

[source,rust]

// Run everything concurrently. // If we had made everything `'static` above instead, we could do this using separate tasks instead. join(usb_fut, join(echo_fut, log_fut)).await;

There are two main ways to handle concurrency in Embassy:

  1. Spawn multiple tasks, e.g. with #[embassy_executor::task]
  2. Manage multiple futures inside ONE task using join() or select() (as shown above)

In general, either of these approaches will work. The main differences of these approaches are:

When using separate tasks, each task needs its own RAM allocation, so there's a little overhead for each task, so one task that does three things will likely be a little bit smaller than three tasks that do one thing (not a lot, probably a couple dozen bytes). In contrast, with multiple futures in one task, you don't need multiple task allocations, and it will generally be easier to share data, or use borrowed resources, inside of a single task.
An example showcasing some methods for sharing things between tasks link:https://github.com/embassy-rs/embassy/blob/main/examples/rp/src/bin/sharing.rs[can be found here].

But when it comes to "waking" tasks, for example when a data transfer is complete or a button is pressed, it's faster to wake a dedicated task, because that task does not need to check which future is actually ready. join and select must check ALL of the futures they are managing to see which one (or which ones) are ready to do more work. This is because all Rust executors (like Embassy or Tokio) only have the ability to wake tasks, not specific futures. This means you will use slightly less CPU time juggling futures when using dedicated tasks.

Practically, there's not a LOT of difference either way - so go with what makes it easier for you and your code first, but there will be some details that are slightly different in each case.

== splitting peripherals resources between tasks

There are two ways to split resources between tasks, either manually assigned or by a convenient macro. See link:https://github.com/embassy-rs/embassy/blob/main/examples/rp/src/bin/assign_resources.rs[this example]

== My code/driver works in debug mode, but not release mode (or with LTO)

Issues like these while implementing drivers often fall into one of the following general causes, which are a good list of common errors to check for:

  1. Some kind of race condition - the faster code means you miss an interrupt or something
  2. Some kind of UB, if you have unsafe code, or something like DMA with fences missing
  3. Some kind of hardware errata, or some hardware misconfiguration like wrong clock speeds
  4. Some issue with an interrupt handler, either enabling, disabling, or re-enabling of interrupts when necessary
  5. Some kind of async issue, like not registering wakers fully before checking flags, or not registering or pending wakers at the right time

== How can I prevent the thread-mode executor from going to sleep? ==

In some cases you might want to prevent the thread-mode executor from going to sleep, for example when doing so would result in current spikes that reduce analog performance.
As a workaround, you can spawn a task that yields in a loop, preventing the executor from going to sleep. Note that this may increase power consumption.

[source,rust]

#[embassy_executor::task]
async fn idle() {
loop { embassy_futures::yield_now().await; }

}

== Why is my bootloader restarting in loop?

== Troubleshooting Bootloader Restart Loops

If your bootloader restarts in a loop, there could be multiple reasons. Here are some things to check:

=== Validate the memory.x File
The bootloader performs critical checks when creating partitions using the addresses defined in memory.x. Ensure the following assertions hold true:

[source,rust]

const {
core::assert!(Self::PAGE_SIZE % ACTIVE::WRITE_SIZE as u32 == 0);
core::assert!(Self::PAGE_SIZE % ACTIVE::ERASE_SIZE as u32 == 0);
core::assert!(Self::PAGE_SIZE % DFU::WRITE_SIZE as u32 == 0);
core::assert!(Self::PAGE_SIZE % DFU::ERASE_SIZE as u32 == 0);
}

// Ensure enough progress pages to store copy progress assert_eq!(0, Self::PAGE_SIZE % aligned_buf.len() as u32); assert!(aligned_buf.len() >= STATE::WRITE_SIZE); assert_eq!(0, aligned_buf.len() % ACTIVE::WRITE_SIZE); assert_eq!(0, aligned_buf.len() % DFU::WRITE_SIZE);

If any of these assertions fail, the bootloader will likely restart in a loop. This failure might not log any messages (e.g., when using defmt). Confirm that your memory.x file and flash memory align with these requirements.

=== Handling Panic Logging
Some panic errors might log messages, but certain microcontrollers reset before the message is fully printed. To ensure panic messages are logged, add a delay using no-operation (NOP) instructions before the reset:

[source,rust]

#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
for _ in 0..10_000_000 {
cortex_m::asm::nop();
}
cortex_m::asm::udf();

}

=== Feed the watchdog

Some embassy-boot implementations (like embassy-boot-nrf and embassy-boot-rp) rely on a watchdog timer to detect application failure. The bootloader will restart if your application code does not properly feed the watchdog timer. Make sure to feed it correctly.


Pages Getting Started (`docs/pages/getting_started.adoc`)

= Getting started

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

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 link:https://github.com/embassy-rs/embassy/tree/main/examples[examples folder] to see if example code has been written for it.

=== nRF kits

=== STM32 kits

=== RP2040 kits

=== ESP32

== Running an example

First you need to clone the link:https://github.com/embassy-rs/embassy[github repository];

[source, bash]

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”.

[source, bash]

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:

[source, bash]

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:

[source]

text
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 link:https://probe.rs/[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: [source]

0.000000 INFO Hello World! └─ 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) } └─ 0.000061 TRACE allocating type=Interrupt mps=8 interval_ms=255, dir=In └─ 0.000091 TRACE index=1 └─

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

[source,toml]

[profile.release] debug = 2

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

[source]

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 link:https://probe.rs/docs/getting-started/installation/[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 link:https://github.com/probe-rs/probe-rs/issues/1849[known to put the pico probe into an unusable state].

:embassy-dev-faq-link-with-hash: https://embassy.dev/book/#_frequently_asked_questions
:embassy-matrix-channel: https://matrix.to/#/#embassy-rs:matrix.org

If you’re still having problems, check the {embassy-dev-faq-link-with-hash}[FAQ], or ask for help in the {embassy-matrix-channel}[Embassy Chat Room].

== What's next?

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

  • Read more about the xref:_embassy_executor[executor].
  • Read more about the xref:_hardware_abstraction_layer_hal[HAL].
  • Start xref:_a_basic_embassy_application[writing your application].
  • Learn how to xref:_starting_a_new_project[start a new embassy project by adapting an example].

Pages Hal (`docs/pages/hal.adoc`)

= Hardware Abstraction Layer (HAL)

Embassy provides HALs for several microcontroller families:

  • embassy-mcxa for MCX-A microcontrollers from NXP.
  • embassy-mspm0 for the MSPM0 and MSPS003 microcontrollers from Texas Instruments
  • embassy-nrf for the nRF microcontrollers from Nordic Semiconductor
  • embassy-stm32 for STM32 microcontrollers from ST Microelectronics
  • embassy-rp for the Raspberry Pi RP2040 and RP235x microcontrollers

Outside of the Embassy project there are several Embassy compatible HALs:

These HALs implement async/await functionality for most peripherals while also implementing the
async traits in embedded-hal and embedded-hal-async. You can also use these HALs with another executor.


Pages Imxrt (`docs/pages/imxrt.adoc`)

= Embassy iMXRT HAL

The link:https://github.com/embassy-rs/embassy/tree/main/embassy-imxrt[Embassy iMXRT HAL] is based on the following PACs (Peripheral Access Crate):

== Peripherals

The following peripherals have a HAL implementation at present

  • CRC
  • DMA
  • GPIO
  • RNG
  • UART

Pages Layer By Layer (`docs/pages/layer_by_layer.adoc`)

= From bare metal to async Rust

If you're new to Embassy, it can be overwhelming to grasp all the terminology and concepts. This guide aims to clarify the different layers in Embassy, which problem each layer solves for the application writer.

This guide uses the STM32 IOT01A board, but should be easy to translate to any STM32 chip. For nRF, the PAC itself is not maintained within the Embassy project, but the concepts and the layers are similar.

The application we'll write is a simple 'push button, blink led' application, which is great for illustrating input and output handling for each of the examples we'll go through. We'll start at the Peripheral Access Crate (PAC) example and end at the async example.

== PAC version

The PAC is the lowest API for accessing peripherals and registers, if you don't count reading/writing directly to memory addresses. It provides distinct types to make accessing peripheral registers easier, but it does little to prevent you from configuring or coordinating those registers incorrectly.

Writing an application using the PAC directly is therefore not recommended, but if the functionality you want to use is not exposed in the upper layers, that's what you need to use.

The blinky app using PAC is shown below:

[source,rust]

include::../examples/layer-by-layer/blinky-pac/src/main.rs[]

As you can see, a lot of code is needed to enable the peripheral clocks and to configure the input pins and the output pins of the application.

Another downside of this application is that it is busy-looping while polling the button state. This prevents the microcontroller from utilizing any sleep mode to save power.

== HAL version

To simplify our application, we can use the HAL instead. The HAL exposes higher level APIs that handle details such as:

  • Automatically enabling the peripheral clock when you're using the peripheral
  • Deriving and applying register configuration from higher level types
  • Implementing the embedded-hal traits to make peripherals useful in third party drivers

The HAL example is shown below:

[source,rust]

include::../examples/layer-by-layer/blinky-hal/src/main.rs[]

As you can see, the application becomes a lot simpler, even without using any async code. The Input and Output types hide all the details of accessing the GPIO registers and allow you to use a much simpler API for querying the state of the button and toggling the LED output.

The same downside from the PAC example still applies though: the application is busy looping and consuming more power than necessary.

== Interrupt driven

To save power, we need to configure the application so that it can be notified when the button is pressed using an interrupt.

Once the interrupt is configured, the application can instruct the microcontroller to enter a sleep mode, consuming very little power.

Given Embassy focus on async Rust (which we'll come back to after this example), the example application must use a combination of the HAL and PAC in order to use interrupts. For this reason, the application also contains some helper functions to access the PAC (not shown below).

[source,rust]

include::../examples/layer-by-layer/blinky-irq/src/main.rs[lines="1..57"]

The simple application is now more complex again, primarily because of the need to keep the button and LED states in the global scope where it is accessible by the main application loop, as well as the interrupt handler.

To do that, the types must be guarded by a mutex, and interrupts must be disabled whenever we are accessing this global state to gain access to the peripherals.

Luckily, there is an elegant solution to this problem when using Embassy.

== Async version

It's time to use the Embassy capabilities to its fullest. At the core, Embassy has an async executor, or a runtime for async tasks if you will. The executor polls a set of tasks (defined at compile time), and whenever a task blocks, the executor will run another task, or put the microcontroller to sleep.

[source,rust]

include::../examples/layer-by-layer/blinky-async/src/main.rs[]

The async version looks very similar to the HAL version, apart from a few minor details:

  • The main entry point is annotated with a different macro and has an async type signature. This macro creates and starts an Embassy runtime instance and launches the main application task. Using the Spawner instance, the application may spawn other tasks.
  • The peripheral initialization is done by the main macro, and is handed to the main task.
  • Before checking the button state, the application is awaiting a transition in the pin state (low -> high or high -> low).

When button.wait_for_any_edge().await is called, the executor will pause the main task and put the microcontroller in sleep mode, unless there are other tasks that can run. On this chip, interrupt signals on EXTI lines 10-15 (including the button on EXTI line 13) raise the hardware interrupt EXTI15_10. This interrupt handler has been bound (using bind_interrupts!) to call the InterruptHandler provided by the exti module, so that whenever an interrupt is raised, the task awaiting the button via wait_for_any_edge() will be woken up.

The minimal overhead of the executor and the ability to run multiple tasks "concurrently" combined with the enormous simplification of the application, makes async a great fit for embedded.

== Summary

We have seen how the same application can be written at the different abstraction levels in Embassy. First starting out at the PAC level, then using the HAL, then using interrupts, and then using interrupts indirectly using async Rust.


Pages Mcxa (`docs/pages/mcxa.adoc`)

= Embassy MCX-A HAL

The link:https://github.com/embassy-rs/embassy/tree/main/embassy-mcxa[Embassy MCX-A HAL] is based on the following PAC (Peripheral Access Crate):

== Chip selection

Select the chip feature, for example mcxa266 or mcxa577.
The compatibility aliases mcxa2xx and mcxa5xx select those two chips respectively.
The _mcxa2xx and _mcxa5xx features are internal register-map groups.

== Peripherals

The following peripherals have a HAL implementation at present

  • Clocks
  • GPIO
  • ADC
  • CLKOUT
  • I2C
  • I3C
  • LPUart
  • OSTimer
  • LPTMR (time-counter mode)
  • RTC
  • SPI controller
  • TRNG
  • WWDT
  • CDOG
  • CTIMER
  • CRC
  • DMA

== Time driver selection

The default time-driver-any feature selects OSTIMER0, preserving the existing
1 MHz time base. Enable time-driver-lptmr to use LPTMR0 instead, or explicitly
select time-driver-ostimer. The two explicit choices are mutually exclusive.
Disable default features and omit all three time-driver features to provide an
external time driver.

The selected peripheral is reserved: its singleton is not returned by init().
The LPTMR backend uses a free-running 1 MHz counter and checks the alarm queue
every 1 ms. Alarm wakeups are never early, but may be delayed by one polling
interval plus interrupt scheduling latency. It produces periodic interrupts
even when no alarms are queued. It requires an always-enabled clk_1m and an
active slow bus clock of at least 2 MHz. Service it (or read the time) at least
once per 32-bit counter wrap, approximately 71 minutes. Like the hardware
counter, this time base pauses while the debugger halts the core.

The standalone LPTMR driver supports polling and interrupt-backed async waits,
free-running or reset-on-compare mode, direct FRO16K or MRCC clock selection,
and counter prescaling. Dropping a pending wait stops the timer. Pulse counting
and DMA are not part of this driver. Configurations producing fractional-Hz
counter clocks are rejected, so duration conversion cannot round a faster
hardware clock down and wake early. Functional clock limits are 22.5 MHz on
MCXA2 and 24 MHz on MCXA5, with the counter increment rate limited to half the
active slow bus clock for reliable snapshots.

Run the lptmr example in examples/mcxa266 or examples/mcxa577 normally to
exercise the standalone driver, or add --features time-driver-lptmr to
exercise the Embassy time backend.


Pages Microchip (`docs/pages/microchip.adoc`)

= Embassy Microchip HAL

The link:https://github.com/embassy-rs/embassy/tree/main/embassy-microchip[Embassy Microchip HAL] is based on the following PAC (Peripheral Access Crate):

== Peripherals

The following peripherals have a HAL implementation at present

  • GPIO
  • I2C
  • PWM
  • TACH
  • Time driver (using the CCT)

Pages New Project (`docs/pages/new_project.adoc`)

= Starting a new project

Once you’ve successfully xref:#_getting_started[run some example projects], the next step is to make a standalone Embassy project.

== Tools for generating Embassy projects

=== CLI

=== cargo-generate

=== esp-generate

== Starting a project from scratch

As an example, let’s create a new embassy project from scratch for a STM32G474. The same instructions are applicable for any supported chip with some minor changes.

Run:

[source,bash]

cargo new stm32g474-example cd stm32g474-example

to create an empty rust project:

[source]

stm32g474-example
├── Cargo.toml
└── src
└── main.rs


Looking in link:https://github.com/embassy-rs/embassy/tree/main/examples[the Embassy examples], we can see there’s a stm32g4 folder. Find src/blinky.rs and copy its contents into our src/main.rs.

=== The .cargo/config.toml

Currently, we’d need to provide cargo with a target triple every time we run cargo build or cargo run. Let’s spare ourselves that work by copying .cargo/config.toml from examples/stm32g4 into our project.

[source]

stm32g474-example
├── .cargo
│   └── config.toml
├── Cargo.toml
└── src
└── main.rs


In addition to a target triple, .cargo/config.toml contains a runner key which allows us to conveniently run our project on hardware with cargo run via probe-rs. In order for this to work, we need to provide the correct chip ID. We can do this by checking probe-rs chip list:

[source,bash]

$ probe-rs chip list | grep -i stm32g474re
STM32G474RETx


and copying STM32G474RETx into .cargo/config.toml as so:

[source,toml]

[target.'cfg(all(target_arch = "arm", target_os = "none"))']

replace STM32G071C8Rx with your chip as listed in `probe-rs chip list`

runner = "probe-rs run --chip STM32G474RETx"

=== Cargo.toml

Now that cargo knows what target to compile for (and probe-rs knows what chip to run it on), we’re ready to add some dependencies.

Looking in examples/stm32g4/Cargo.toml, we can see that the examples require a number of embassy crates. For blinky, we’ll only need three of them: embassy-stm32, embassy-executor and embassy-time.

At the time of writing, embassy is already published to crates.io. Therefore, dependencies can easily be added in Cargo.toml.

[source,toml]

[dependencies] embassy-stm32 = { version = "0.1.0", features = ["defmt", "time-driver-any", "stm32g474re", "memory-x", "unstable-pac", "exti"] } embassy-executor = { version = "0.6.3", features = ["nightly", "platform-cortex-m", "executor-thread", "defmt"] } embassy-time = { version = "0.3.2", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }

Previously, embassy needed to be installed straight from the git repository. Installing from git is still useful, if you want to checkout a specific revision of an embassy crate which is not yet published.
The recommended way of doing so is:

  • Copy the required embassy-* lines from the example Cargo.toml
  • Make any necessary changes to features, e.g. requiring the stm32g474re feature of embassy-stm32
  • Remove the path = "" keys in the embassy-* entries
  • Create a [patch.crates-io] section, with entries for each embassy crate we need. These should all contain identical values: a link to the git repository, and a reference to the commit we’re checking out. Assuming you want the latest commit, you can find it by running git ls-remote https://github.com/embassy-rs/embassy.git HEAD

NOTE: When using this method, it’s necessary that the version keys in [dependencies] match up with the versions defined in each crate’s Cargo.toml in the specificed rev under [patch.crates.io]. This means that when updating, you have to a pick a new revision, change everything in [patch.crates.io] to match it, and then correct any versions under [dependencies] which have changed.

An example Cargo.toml file follows. Note that the version values must match the versions defined in the embassy crates at the git revision you are checking out, which may differ from the latest published versions on crates.io:

[source,toml]

[dependencies]
embassy-stm32 = {version = "0.1.0", features = ["defmt", "time-driver-any", "stm32g474re", "memory-x", "unstable-pac", "exti"]}
embassy-executor = { version = "0.6.3", features = ["platform-cortex-m", "executor-thread", "defmt"] }
embassy-time = { version = "0.3.2", features = ["defmt", "defmt-timestamp-uptime", "tick-hz-32_768"] }

[patch.crates-io] embassy-time = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" } embassy-executor = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" } embassy-stm32 = { git = "https://github.com/embassy-rs/embassy", rev = "7703f47c1ecac029f603033b7977d9a2becef48c" }

There are a few other dependencies we need to build the project, but fortunately they’re much simpler to install. Copy their lines from the example Cargo.toml to the [dependencies] section in the new Cargo.toml:

[source,toml]

defmt = "0.3.5" defmt-rtt = "0.4.0" cortex-m = {version = "0.7.7", features = ["critical-section-single-core"]} cortex-m-rt = "0.7.3" panic-probe = "0.3.1"

These are the bare minimum dependencies required to run blinky.rs, but it’s worth taking a look at the other dependencies specified in the example Cargo.toml, and noting what features are required for use with embassy – for example futures = { version = "0.3.17", default-features = false, features = ["async-await"] }.

Finally, copy the [profile.release] section from the example Cargo.toml into ours:

[source,toml]

[profile.release] debug = 2

=== rust-toolchain.toml

Before we can build our project, we need to add an additional file to tell cargo which toolchain to use. Copy the rust-toolchain.toml from the embassy repo to ours, and trim the list of targets down to only the target triple relevent for our project — in this case, thumbv7em-none-eabi:

[source]

stm32g474-example
├── .cargo
│   └── config.toml
├── Cargo.toml
├── rust-toolchain.toml
└── src
└── main.rs


[source,toml]

Before upgrading check that everything is available on all tier1 targets here:

https://rust-lang.github.io/rustup-components-history

[toolchain] channel = "1.85" components = [ "rust-src", "rustfmt", "llvm-tools", "miri" ] targets = ["thumbv7em-none-eabi"]

=== build.rs

In order to produce a working binary for our target, cargo requires a custom build script. Copy build.rs from the example to our project:

[source]

stm32g474-example
├── build.rs
├── .cargo
│ └── config.toml
├── Cargo.toml
├── rust-toolchain.toml
└── src
└── main.rs


=== Building and running

At this point, we‘re finally ready to build and run our project! Connect your board via a debug probe and run:

[source,bash]

cargo run --release

should result in a blinking LED (if there’s one attached to the pin in src/main.rs – change it if not!) and the following output:

[source]

Compiling stm32g474-example v0.1.0 (/home/you/stm32g474-example)
Finished release [optimized + debuginfo] target(s) in 0.22s
Running probe-rs run --chip STM32G474RETx target/thumbv7em-none-eabi/release/stm32g474-example
Erasing sectors ✔ [00:00:00] [#########################################################] 18.00 KiB/18.00 KiB @ 54.09 KiB/s (eta 0s )
Programming pages ✔ [00:00:00] [#########################################################] 17.00 KiB/17.00 KiB @ 35.91 KiB/s (eta 0s ) Finished in 0.817s
0.000000 TRACE BDCR configured: 00008200
└─ embassy_stm32::rcc::bd::{impl#3}::init::{closure#4} @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:117
0.000000 DEBUG rcc: Clocks { sys: Hertz(16000000), pclk1: Hertz(16000000), pclk1_tim: Hertz(16000000), pclk2: Hertz(16000000), pclk2_tim: Hertz(16000000), hclk1: Hertz(16000000), hclk2: Hertz(16000000), pll1_p: None, adc: None, adc34: None, rtc: Some(Hertz(32000)) }
└─ embassy_stm32::rcc::set_freqs @ /home/you/.cargo/git/checkouts/embassy-9312dcb0ed774b29/7703f47/embassy-stm32/src/fmt.rs:130
0.000000 INFO Hello World!
└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:14
0.000091 INFO high
└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:19
0.300201 INFO low

└─ embassy_stm32g474::____embassy_main_task::{async_fn#0} @ src/main.rs:23


Pages Nrf (`docs/pages/nrf.adoc`)

= Embassy nRF HAL

The link:https://github.com/embassy-rs/embassy/tree/main/embassy-nrf[Embassy nRF HAL] is based on the PACs (Peripheral Access Crate) from link:https://github.com/nrf-rs/[nrf-rs].

== Timer driver

The nRF timer driver operates at 32768 Hz by default.

== Peripherals

The following peripherals have a HAL implementation at present

  • PWM
  • SPIM
  • QSPI
  • NVMC
  • GPIOTE
  • RNG
  • TIMER
  • WDT
  • TEMP
  • PPI
  • UARTE
  • TWIM
  • SAADC

== Bluetooth

For bluetooth, you can use the link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] crate.


Pages Overview (`docs/pages/overview.adoc`)

= 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 link:https://docs.embassy.dev/embassy-executor/[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.

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 link:https://github.com/rust-embedded/embedded-hal[Embedded HAL] blocking and async traits.

=== Networking
The link:https://docs.embassy.dev/embassy-net/[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 link:https://docs.embassy.dev/embassy-ptp-driver/[embassy-ptp-driver] crate defines a network-stack-independent interface for reading and adjusting PTP hardware clocks.

=== Bluetooth

=== LoRa
link:https://github.com/lora-rs/lora-rs[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
link:https://docs.embassy.dev/embassy-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
link:https://github.com/embassy-rs/embassy/tree/main/embassy-boot[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

[source,rust]

include::../examples/examples/std/src/bin/tick.rs[]

include::embassy_in_the_wild.adoc[leveloffset = 2]

== Resources

For more reading material on async Rust and Embassy:

Videos:


Pages Project Structure (`docs/pages/project_structure.adoc`)

= Project Structure

There are many ways to configure embassy and its components for your exact application. The link:https://github.com/embassy-rs/embassy/tree/main/examples[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: [source,plain]

{} = Maybe

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

[discrete]
== .cargo/config.toml

This directory/file describes what platform you're on, and configures link:https://github.com/probe-rs/probe-rs[probe-rs] to deploy to your device.

Here is a minimal example:

[source,toml]

[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

[discrete]
== build.rs

This is the build script for your project. It links defmt (what is link:https://defmt.ferrous-systems.com[defmt]?) and the memory.x file if needed. This file is pretty specific for each chipset, just copy and paste from the corresponding link:https://github.com/embassy-rs/embassy/tree/main/examples[example].

[discrete]
== Cargo.toml

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

[discrete]
=== Features

[discrete]
==== 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

[discrete]
== memory.x

This file outlines the flash/ram usage of your program. It is especially useful when using link:https://github.com/embassy-rs/nrf-softdevice[nrf-softdevice] on an nRF5x.

Here is an example for using S140 with an nRF52840:

[source,x]

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 }

[discrete]
== rust-toolchain.toml

This file configures the rust version and configuration to use.

A minimal example:

[source,toml]

[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

]


Pages Runtime (`docs/pages/runtime.adoc`)

= Embassy executor

The Embassy executor is an async/await executor designed for embedded usage along with support functionality for interrupts and timers.

== Features

  • No alloc, no heap needed. Tasks are statically allocated.
  • No "fixed capacity" data structures, executor works with 1 or 1000 tasks without needing config/tuning.
  • Integrated timer queue: sleeping is easy, just do Timer::after_secs(1).await;.
  • No busy-loop polling: CPU sleeps when there's no work to do, using interrupts or WFE/SEV.
  • Efficient polling: a wake will only poll the woken task, not all of them.
  • Fair: a task can't monopolize CPU time even if it's constantly being woken. All other tasks get a chance to run before a given task gets polled for the second time.
  • Multiple executor instances can be created, to run tasks at different priority levels. This allows higher-priority tasks to preempt lower-priority tasks.

== Executor

The executor works as follows:

. When a task is created, it is polled.
. The task attempts to make progress until it reaches a point where it would be blocked. This may happen whenever a task is .await-ing an async function. When that happens, the task yields execution by returning Poll::Pending.
. Once a task yields, the executor enqueues the task at the end of the run queue and proceeds to poll the next task in the queue.

When a task is finished or canceled, it will not be enqueued again.

IMPORTANT: The executor relies on tasks not blocking indefinitely, this would prevent the executor regaining control and scheduling another task.

image::embassy_executor.png[Executor model]

If you use the #[embassy_executor::main] macro in your application, it creates the Executor for you and spawns the main entry point as the first task. You can also create the Executor manually, and you can in fact create multiple Executors.

== Interrupts

Interrupts are a common way for peripherals to signal completion of some operation and fits well with the async execution model. The following diagram describes a typical application flow where (1) a task is polled and is attempting to make progress. The task then (2) instructs the peripheral to perform some operation, and awaits. After some time has passed, (3) an interrupt is raised, marking the completion of the operation.

The peripheral HAL then (4) ensures that interrupt signals are routed to the peripheral and updates the peripheral state with the results of the operation. The executor is then (5) notified that the task should be polled, which it will do.

image::embassy_irq.png[Interrupt handling]

NOTE: A special executor named InterruptExecutor can be driven by an interrupt. This can be used to drive tasks at different priority levels by creating multiple InterruptExecutor instances.

== Time

Embassy features an internal timer queue enabled by the time feature flag. When enabled, Embassy assumes that a time Driver implementation exists for the platform. Embassy provides time drivers for the nRF, STM32, RPi Pico, WASM and Std platforms.

NOTE: Some embedded platforms' timer drivers might only support a limited number of alarms. Make sure that the number of tasks using the timer simultaneously do not exceed this limit.

The timer speed is configurable at compile time using the time-tick-<frequency>. At present, the timer may be configured to run at 1000 Hz, 32768 Hz, or 1 MHz. Before changing the defaults, make sure the target HAL supports the particular frequency setting.

NOTE: If you do not require timers in your application, not enabling the time feature can save some CPU cycles and reduce power usage.


Pages Sharing Peripherals (`docs/pages/sharing_peripherals.adoc`)

= Sharing peripherals between tasks

Often, more than one task needs to access the same resource (pin, communication interface, etc.). Embassy provides many different synchronization primitives in the link:https://crates.io/crates/embassy-sync[embassy-sync] crate.

The following examples show different ways for two tasks to use the on-board LED on a Raspberry Pi Pico board simultaneously.

== Sharing using a Mutex

Using mutual exclusion is the simplest way to share a peripheral.

use defmt::*;
use embassy_executor::Spawner;
use embassy_rp::gpio;
use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;
use embassy_sync::mutex::Mutex;
use embassy_time::{Duration, Ticker};
use gpio::{AnyPin, Level, Output};
use {defmt_rtt as _, panic_probe as _};

type LedType = Mutex>>;
static LED: LedType = Mutex::new(None);

#[embassy_executor::main]
async fn main(spawner: Spawner) {
let p = embassy_rp::init(Default::default());
// set the content of the global LED reference to the real LED pin
let led = Output::new(AnyPin::from(p.PIN_25), Level::High);
// inner scope is so that once the mutex is written to, the MutexGuard is dropped, thus the
// Mutex is released
{
*(LED.lock().await) = Some(led);
}
let dt = 100 * 1_000_000;
let k = 1.003;

text
unwrap!(spawner.spawn(toggle_led(&LED, Duration::from_nanos(dt))));
unwrap!(spawner.spawn(toggle_led(&LED, Duration::from_nanos((dt as f64 * k) as u64))));

}

// A pool size of 2 means you can spawn two instances of this task.
#[embassy_executor::task(pool_size = 2)]
async fn toggle_led(led: &'static LedType, delay: Duration) {
let mut ticker = Ticker::every(delay);
loop {
{
let mut led_unlocked = led.lock().await;
if let Some(pin_ref) = led_unlocked.as_mut() {
pin_ref.toggle();
}
}
ticker.next().await;
}

}

The structure facilitating access to the resource is the defined LedType.

=== Why so complicated

Unwrapping the layers gives insight into why each one is needed.

==== Mutex<RawMutexType, T>

The mutex is there so if one task gets the resource first and begins modifying it, all other tasks wanting to write will have to wait (the led.lock().await will return immediately if no task has locked the mutex, and will block if it is accessed somewhere else).

==== Option<T>

The LED variable needs to be defined outside the main task as references accepted by tasks need to be 'static. However, if it is outside the main task, it cannot be initialised to point to any pin, as the pins themselves are not initialised. Thus, it is set to None.

==== Output<AnyPin>

To indicate that the pin will be set to an Output. The AnyPin could have been embassy_rp::peripherals::PIN_25, however this option lets the toggle_led function be more generic.

== Sharing using a Channel

A channel is another way to ensure exclusive access to a resource. Using a channel is great in the cases where the access can happen at a later point in time, allowing you to enqueue operations and do other things.

use defmt::*;
use embassy_executor::Spawner;
use embassy_rp::gpio;
use embassy_sync::blocking_mutex::raw::ThreadModeRawMutex;
use embassy_sync::channel::{Channel, Sender};
use embassy_time::{Duration, Ticker};
use gpio::{AnyPin, Level, Output};
use {defmt_rtt as _, panic_probe as _};

enum LedState {
Toggle,
}
static CHANNEL: Channel = Channel::new();

#[embassy_executor::main]
async fn main(spawner: Spawner) {
let p = embassy_rp::init(Default::default());
let mut led = Output::new(AnyPin::from(p.PIN_25), Level::High);

text
let dt = 100 * 1_000_000;
let k = 1.003;

unwrap!(spawner.spawn(toggle_led(CHANNEL.sender(), Duration::from_nanos(dt))));
unwrap!(spawner.spawn(toggle_led(CHANNEL.sender(), Duration::from_nanos((dt as f64 * k) as u64))));

loop {
    match CHANNEL.receive().await {
        LedState::Toggle => led.toggle(),
    }
}

}

// A pool size of 2 means you can spawn two instances of this task.
#[embassy_executor::task(pool_size = 2)]
async fn toggle_led(control: Sender<'static, ThreadModeRawMutex, LedState, 64>, delay: Duration) {
let mut ticker = Ticker::every(delay);
loop {
control.send(LedState::Toggle).await;
ticker.next().await;
}

}

This example replaces the Mutex with a Channel, and uses another task (the main loop) to drive the LED. The advantage of this approach is that only a single task references the peripheral, separating concerns. However, using a Mutex has a lower overhead and might be necessary if you need to ensure
that the operation is completed before continuing to do other work in your task.

An example showcasing more methods for sharing link:https://github.com/embassy-rs/embassy/blob/main/examples/rp/src/bin/sharing.rs[can be found here].

== Sharing an I2C or SPI bus between multiple devices

An example of how to deal with multiple devices sharing a common I2C or SPI bus link:https://github.com/embassy-rs/embassy/blob/main/examples/rp/src/bin/shared_bus.rs[can be found here].


Pages Stm32 (`docs/pages/stm32.adoc`)

= Embassy STM32 HAL

The link:https://github.com/embassy-rs/embassy/tree/main/embassy-stm32[Embassy STM32 HAL] is based on the stm32-metapac project.

== The infinite variant problem

STM32 microcontrollers come in many families, and flavors and supporting all of them is a big undertaking. Embassy has taken advantage of the fact
that the STM32 peripheral versions are shared across chip families. Instead of re-implementing the SPI
peripheral for every STM32 chip family, embassy has a single SPI implementation that depends on
code-generated register types that are identical for STM32 families with the same version of a given peripheral.

=== The metapac

The stm32-metapac module uses pre-generated chip and register definitions for STM32 chip families to generate register types. This is done at compile time based on Cargo feature flags.

The chip and register definitions are located in a separate module, stm32-data, which is modified whenever a bug is found in the definitions, or when adding support for new chip families.

=== The HAL

The embassy-stm32 module contains the HAL implementation for all STM32 families. The implementation uses automatically derived feature flags to support the correct version of a given peripheral for a given chip family.

== Timer driver

The STM32 timer driver operates at 32768 Hz by default.


Pages System (`docs/pages/system.adoc`)

= System description

This section describes different parts of Embassy in more detail.

include::runtime.adoc[leveloffset = 2]
include::bootloader.adoc[leveloffset = 2]
include::time_keeping.adoc[leveloffset = 2]
include::hal.adoc[leveloffset = 2]
include::imxrt.adoc[leveloffset = 2]
include::mcxa.adoc[leveloffset = 2]
include::nrf.adoc[leveloffset = 2]
include::stm32.adoc[leveloffset = 2]
include::sharing_peripherals.adoc[leveloffset = 2]


Pages Time Keeping (`docs/pages/time_keeping.adoc`)

= Time-keeping

In an embedded program, delaying a task is one of the most common actions taken. In an event loop, delays will need to be inserted to ensure
that other tasks have a chance to run before the next iteration of the loop is called, if no other I/O is performed. Embassy provides abstractions
to delay the current task for a specified interval of time.

The interface for time-keeping in Embassy is handled by the link:https://crates.io/crates/embassy-time[embassy-time] crate. The types can be used with the internal
timer queue in link:https://crates.io/crates/embassy-executor[embassy-executor] or a custom timer queue implementation.

== Timer

The embassy_time::Timer type provides two timing methods.

Timer::at creates a future that completes at the specified Instant, relative to the system boot time.
Timer::after creates a future that completes after the specified Duration, relative to when the future was created.

An example of a delay is provided as follows:

use embassy_executor::task;
use embassy_time::{Duration, Timer};

#[task]
/// Task that ticks periodically
async fn tick_periodic() -> ! {
loop {
rprintln!("tick!");
// async sleep primitive, suspends the task for 500ms.
Timer::after(Duration::from_millis(500)).await;
}

}

== Delay

The embassy_time::Delay type provides an implementation of the link:https://docs.rs/embedded-hal/1.0.0/embedded_hal/delay/index.html[embedded-hal] and
link:https://docs.rs/embedded-hal-async/latest/embedded_hal_async/delay/index.html[embedded-hal-async] traits. This can be used for drivers
that expect a generic delay implementation to be provided.

An example of how this can be used:

use embassy_executor::task;
use embassy_time::Delay;

#[task]
/// Task that ticks periodically
async fn tick_periodic() -> ! {
loop {
rprintln!("tick!");
// async sleep primitive, suspends the task for 500ms.
generic_delay(Delay).await
}
}

async fn generic_delay<D: embedded_hal_async::delay::DelayNs>(delay: D) {
delay.delay_ms(500).await;

}


--- METRICS ---