type
status
slug
date
summary
tags
category
password
icon
I took notes from the book above☝️
👇
A Simple Tour for EmbassyWhat is async?What is Embassy?ExecutorHardware Abstraction LayersNetworkingBluetoothLoRaUSBBootloader and DFUWhat is DMA?My usage of exampleA basic Embassy application(My for stm32F401)MainDealing with errorsTask declarationMainThe Cargo.toml.cargo/config.tomlbuild.rsCargo.tomlmemory.xrust-toolchain.tomlStarting a new projectTools for generating Embassy projectsCLIcargo-generateStarting a project from scratchFrom bare metal to async RustPAC versionHAL versionInterrupt drivenAsync versionSummarySystem descriptionEmbassy executorFeaturesExecutorInterruptsTimeBootloaderHardware supportDesignFirmwareUpdaterTime-keepingTimerDelayHardware Abstraction Layer (HAL)Let’s talk about the support for stm32Embassy STM32 HALThe infinite variant problemThe metapacThe HALTimer driverDeveloper Documentation: STM32Understanding metapacstm32-data-sourcesstm32-dataembassy-stm32Sharing peripherals between tasksSharing using a MutexWhy so complicatedSharing using a ChannelThings should shareFrequently Asked Questions(For me which I take notes)The memory definition for my STM chip seems wrong, how do I define a memory.x file?trouble shooting 1、if you encounter:2、if you config debug in vscode with wrong path 3、No peripheral view?4、I want to use GDB and OPENOCD while also want to see the output from defmtno such command : defmt-print rust???material I use, hope can help you.Plan to initiate my project
A Simple Tour for Embassy
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 they do not transfer control back to the kernel within an allotted time. If tasks could be presumed to behave cooperatively, or at least not maliciously, it would be possible to create tasks that appear to be almost free when compared to a traditional OS thread.
In other programming languages, these lightweight tasks are known as “coroutines” or ”goroutines”. In Rust, they are implemented with async. Async-await works by transforming each async function into an object called a future. When a future blocks on I/O the future yields, and the scheduler, called an executor, can select a different future to execute.
Compared to alternatives such as an RTOS, async can yield better performance and lower power consumption because the executor doesn’t have to guess when a future is ready to execute. However, program size may be higher than other alternatives, which may be a problem for certain space-constrained devices with very low memory. On the devices Embassy supports, such as stm32 and nrf, memory is generally large enough to accommodate the modestly-increased program size.
What is Embassy?
The Embassy project consists of several crates that you can use together or independently:
Executor
The embassy-executor is an async/await executor that generally executes a fixed number of tasks, allocated at startup, though more can be added later. The executor may also provide a system timer that you can use for both async and blocking delays. For less than one microsecond, blocking delays should be used because the cost of context-switching is too high and the executor will be unable to provide accurate timing.
Hardware Abstraction Layers
HALs implement safe Rust API which let you use peripherals such as USART, UART, I2C, SPI, CAN, and USB without having to directly manipulate registers.
Embassy provides implementations of both async and blocking APIs where it makes sense. DMA (Direct Memory Access) is an example where async is a good fit, whereas GPIO states are a better fit for a blocking API.
The Embassy project maintains HALs for select hardware, but you can still use HALs from other projects with Embassy.
- embassy-stm32, for all STM32 microcontroller families.
- embassy-nrf, for the Nordic Semiconductor nRF52, nRF53, nRF91 series.
- embassy-rp, for the Raspberry Pi RP2040 microcontroller.
- esp-rs, for the Espressif Systems ESP32 series of chips.
- ch32-hal, for the WCH 32-bit RISC-V(CH32V) series of chips.
NOTE | A common question is if one can use the Embassy HALs standalone. Yes, it is possible! There are no dependency on the executor within the HALs. You can even use them without async, as they implement both the Embedded HAL blocking and async traits. |
Networking
The embassy-net network stack implements extensive networking functionality, including Ethernet, IP, TCP, UDP, ICMP and DHCP. Async drastically simplifies managing timeouts and serving multiple connections concurrently. Several drivers for WiFi and Ethernet chips can be found.
Bluetooth
The nrf-softdevice crate provides Bluetooth Low Energy 4.x and 5.x support for nRF52 microcontrollers.
LoRa
lora-rs supports LoRa networking on a wide range of LoRa radios, fully integrated with a Rust LoRaWAN implementation. It provides four crates — lora-phy, lora-modulation, lorawan-encoding, and lorawan-device — and basic examples for various development boards. It has support for STM32WL wireless microcontrollers or Semtech SX127x transceivers, among others.
USB
embassy-usb implements a device-side USB stack. Implementations for common classes such as USB serial (CDC ACM) and USB HID are available, and a rich builder API allows building your own.
Bootloader and DFU
embassy-boot is a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks.
What is DMA?
For most I/O in embedded devices, the peripheral doesn’t directly support the transmission of multiple bits 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.
My usage of example
first of all, install probe-rs:
probe-rs
is an embedded debugging and target interaction toolkit. It enables its user to program and debug microcontrollers via a debug probe.probe-rs
helps you with
- Flashing firmware to
ARM
andRISC-V
targets. More architectures are in the works.
- Reading and writing memory, running, halting, setting and reading breakpoints and resetting the target via
SWD
andJTAG
.
- Running firmware on the target and getting back logs via
RTT
anddefmt
and printing a stacktrace on panic.
- Debugging the target via
VS Code
with runningRTT
logs, memory inspection and more.
if you are using wsl2 as a develop machine, you need to connect you device via usbipd tool:
then you need to clone the github repository;
Once you have a copy of the repository, find examples folder for your board and, 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”.we need to change the device to stm32f401re,where we can find its name in probe-rs by :
is’s name is :STM32F401RETx,change the examples/stm32f4/.cargo/config.toml:
then we can:
Once you’ve confirmed you can build the example, connect your computer to your board with a debug probe and run it on hardware:
A basic Embassy application(My for stm32F401)
As the tutorial use the case of nrf, I will follow it and take notes in the following. But I’ll finally change it to my stm32F401 later .
Let’s go through a simple Embassy application for the nRF52 DK to understand it better.
Main
The full example can be found here.
NOTE | If you’re using VS Code and rust-analyzer to view and edit the examples, you may need to make some changes to .vscode/settings.json to tell it which project we’re working on. Follow the instructions commented in that file to get rust-analyzer working correctly. |
Bare metal
The first thing you’ll notice are two attributes at the top of the file. These tells the compiler that program has no access to std, and that there is no main function (because it is not run by an OS).
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:Task declaration
After a bit of import declaration, the tasks run by the application should be declared:
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:What happens when the
blinker
task has been spawned and main returns? Well, the main entry point is actually just like any other task, except that you can only have one and it takes some specific type arguments. The magic lies within the #[embassy_executor::main]
macro. The macro does the following:1. Creates an Embassy Executor
2. Defines a main task for the entry point
3. Runs the executor spawning the main task
There is also a way to run the executor without using the macro, in which case you have to create the
Executor
instance yourself.The Cargo.toml
The project definition needs to contain the embassy dependencies:
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.
.cargo/config.toml
This directory/file describes what platform you’re on, and configures probe-rs to deploy to your device.
Here is a minimal example:
build.rs
This is the build script for your project. It links defmt (what is defmt?) and the
memory.x
file if needed(I decide to change it to linker.ld and config this to .cargo/config.toml). This file is pretty specific for each chipset, just copy and paste from the corresponding example.Cargo.toml
This is your manifest file, where you can configure all of the embassy components to use the features you need.
Features
Time
- tick-hz-x: Configures the tick rate of
embassy-time
. Higher tick rate means higher precision, and higher CPU wakes.
- defmt-timestamp-uptime: defmt log entries will display the uptime in seconds.
…more to come
memory.x
This file outlines the flash/ram usage of your program. It is especially useful when using nrf-softdevice on an nRF5x.
Here is an example for using S140 with an nRF52840:
rust-toolchain.toml
This file configures the rust version and configuration to use.
A minimal example:
Starting a new project
Once you’ve successfully run some example projects, the next step is to make a standalone Embassy project.
Tools for generating Embassy projects
CLI
- cargo-embassy (STM32 and NRF)
cargo-generate
- embassy-template (STM32, NRF, and RP)
But I prefer first make a minimal demo for myself.
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.
As an example, let’s create a new embassy project from scratch for a STM32G474(Wow, I feel it will be much easy to change it to a f401). The same instructions are applicable for any supported chip with some minor changes.
Run:
to create an empty rust project:
Looking in the Embassy examples, we can see there’s a
stm32g4
folder. Find src/blinky.rs
and copy its contents into our src/main.rs
.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.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
:and copying
STM32G474RETx
into .cargo/config.toml
as so: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
.
as the following method is easy and I need to adopt to my stm32F401, So I will ignore the notes here.
well, I finished the F401’s adopt, easy with the HAL support, give the repo below:
embassy_learn
KMSorSMS • Updated Jun 15, 2024
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 not prevent you from writing unsafe code.
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:
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.
However, I found the code above can’t easily run. Seems the guide missing some setup for this example code.
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:
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).
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.
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.await_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. Internally, the Embassy HAL has configured the interrupt handler for the button (in ExtiButton
), so that whenever an interrupt is raised, the task awaiting the button 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.
System description
This section describes different parts of Embassy in more detail.
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. Task 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.
- Creating multiple executor instances is supported, to run tasks at different priority levels. This allows higher-priority tasks to preempt lower-priority tasks.
Executor
The executor function is described below. The executor keeps a queue of tasks that it should poll.
When a task is created, it is polled (1).
The task will attempt 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 (2) returning
Poll::Pending
. Once a task yields, the executor enqueues the task at the end of the run queue, and proceeds to (3) 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, as this prevents the executor to regain control and schedule another task. |
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 updating 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.
NOTE | There exists a special executor named InterruptExecutor which 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 a time Driver
implementation existing for the platform. Embassy provides time drivers for the nRF, STM32, RPi Pico, WASM and Std platforms.The timer driver implementations for the embedded platforms might support only a fixed number of alarms that can be set. Make sure the number of tasks you expect wanting to use the timer at the same time 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. |
Bootloader
embassy-boot
a lightweight bootloader supporting firmware application upgrades in a power-fail-safe way, with trial boots and rollbacks.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
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.
Design
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 = Partition + Page
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 given by:
Partition = Write + (2 × Partition / Page )
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 one word per page in the ACTIVE and DFU partitions combined.
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.As following part of bootloader is verification, I ignore it and when I need to use I will back to complete the notes.
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 embassy-time crate. The types can be used with the internal timer queue in 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:
TIP | Dependencies needed to run this example can be found here. |
👆the link seems expiration.
Delay
The
embassy::time::Delay
type provides an implementation of the embedded-hal and 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:
TIP | Dependencies needed to run this example can be found here. |
also expired😢
Hardware Abstraction Layer (HAL)
Embassy provides HALs for several microcontroller families:
embassy-nrf
for the nRF microcontrollers from Nordic Semiconductor
embassy-stm32
for STM32 microcontrollers from ST Microelectronics
embassy-rp
for the Raspberry Pi RP2040 microcontrollers
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.Let’s talk about the support for stm32
Embassy STM32 HAL
The 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.stm32-data
embassy-rs • Updated Jun 17, 2024
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.
Developer Documentation: 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 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
stm32-data-sources
is as 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 STM32F051K4Ux.xml
. In that file, you’ll see lines like the following: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 acheive 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
: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
: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:And in the
mod.rs
of the i2c mod, you’ll see this: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.Sharing peripherals between tasks
Often times, more than one task needs access to the same resource (pin, communication interface, etc.). Embassy provides many different synchronization primitives in the embassy-sync crate.
The following examples shows different ways to use the on-board LED on a Raspberry Pi Pico board by two tasks simultaneously.
Sharing using a Mutex
Using mutual exclusion is the simplest way to share a peripheral.
TIP | Dependencies needed to run this example can be found here. |
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.
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.
Things should share
☝️: I found that contrast really cheering, can’t wait to adopt embassy into my project.
Frequently Asked Questions(For me which I take notes)
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: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.
trouble shooting
1、if you encounter:
I recommend read this as I met this error too.
unfortunately, I stuck into a exception, maybe the code in stm32F429 has different with f401,so I decide to write a demo for myself to solve the problem. On going…
2、if you config debug in vscode with wrong path
consider change it in launch.json
3、No peripheral view?
check the path to your svd file, because the extension could work even when you didn’t write it right, so perhaps you can first write it as an absolute path and then change it to relative.
4、I want to use GDB and OPENOCD while also want to see the output from defmt
why I want to use OPENOCD?
because the GDB server implementation in
probe-rs
is not quite as mature as OpenOCD: for example, breakpoints work but stepping operations do not work reliably. With that JSON file the debugger is in place but there are no
defmt
logs yet. To print those logs you'll need to get the defmt
data out of the device, decode it and then print it to the console. defmt-print
, another knurling tool, handles the last 2 steps: it decodes defmt
data from standard input and prints the logs to the console, using the same format as probe-run
.
To get the RTT (defmt
's default transport) data out of the device we can use OpenOCD's RTT support. Here's how:
no such command : defmt-print rust???
Thinking I need to download the src from
defmt
knurling-rs • Updated Jun 22, 2024
and compile it myself to use defmt-print command line
well done.
the gdb runs this:
all works with the reference material above.
I want to notice who use probe rs to debug. unfortunately it was not as good as openocd, especially in gui mode. So I recommend not use it.
material I use, hope can help you.
Plan to initiate my project
stm32f401_embassy
KMSorSMS • Updated Jun 24, 2024
- 作者:liamY
- 链接:https://liamy.clovy.top/article/OScamp_prj6_task01
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。