大使馆:现代嵌入式框架,使用 Rust 和异步编程。
Embassy: Modern embedded framework, using Rust and async

原始链接: https://github.com/embassy-rs/embassy

## 大使馆:使用 Rust 进行下一代嵌入式开发 大使馆是一个框架,旨在简化和加速使用 Rust 编程语言的嵌入式应用程序开发。它利用 Rust 的安全性、效率和异步能力,在*无需*传统 RTOS 的复杂性的情况下,创建健壮且节能的嵌入式系统。 主要功能包括:编译时异步运行时,消除动态内存分配和每个任务的堆栈调整;针对各种微控制器(STM32、nRF、RP2040、MSPM0、ESP32、CH32、MPFS、PY32)的安全且惯用的硬件抽象层 (HAL);以及具有全局可用、防溢出的可靠时间管理。 大使馆还提供对网络(以太网、TCP/UDP)、蓝牙、LoRa、USB 和防掉电安全启动加载器的内置支持。开发通过 Rust Analyzer 和按目标芯片分类的示例集合简化。 大使馆需要 Rust 1.75 或更高版本,并采用 Apache 2.0 或 MIT 许可,为项目提供灵活性。它的目标是使嵌入式开发更快、更安全、更有趣。

## 大使馆:嵌入式系统的现代 Rust 框架 “大使馆”项目 ([github.com/embassy-rs](https://github.com/embassy-rs)) 正在成为一个现代嵌入式框架,它基于 Rust 和异步编程构建。用户称赞它能够在单核芯片上*无需*堆或传统 RTOS 的情况下实现并发,提供低成本的抽象和简化的复杂性。 讨论强调了异步 Rust 在嵌入式开发中的优势,使得 MCU 的选择越来越受到 Rust 兼容性的影响。 推荐了几款用于实验的 MCU,包括 ESP32-C3/C6、Nordic nRF52840 和 Raspberry Pi Pico (RP2040)。 虽然功能强大,但一些用户指出其生态系统仍在发展中,可能存在 API 变更,并且倾向于异步优先的设计,这可能不适合所有项目。 然而,像 `rp-hal` 和 `Debug Probe` 这样的工具正在使 Rust 嵌入式开发更易于访问。像 Ariel OS 这样的项目构建在*大使馆*之上,甚至微软也在将其用于嵌入式控制器。 核心优势是在异步操作期间通过自动 CPU 睡眠状态实现高效的功耗。
相关文章

原文

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.

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!

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

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

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 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 chip.
  • examples/std are designed to run locally on your PC.
  • Install probe-rs following the instructions at https://probe.rs.
  • Change directory to the sample's base directory. For example:
  • 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:

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 stable Rust 1.75 and up. It might compile with older versions, but that may change in any new patch release.

EMBedded ASYnc! :)

Embassy is licensed under either of

at your option.

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.

联系我们 contact @ memedata.com