嵌入式 Rust:从零搭建 no_std 环境

嵌入式 Rust:从零搭建 no_std 环境

嵌入式开发长期被 C 语言主导,但 Rust 的零成本抽象和内存安全保证,使其成为嵌入式开发的有力竞争者。本文以 STM32F4 为目标平台,从零搭建嵌入式 Rust 开发环境。

项目初始化和配置:

示意图
示意图
# 安装交叉编译目标和工具
rustup target add thumbv7em-none-eabihf
cargo install cargo-flash probe-rs

# Cargo.toml
[package]
name = "stm32-blink"
edition = "2021"

[dependencies]
cortex-m = "0.7"
cortex-m-rt = "0.7"
stm32f4xx-hal = { version = "0.20", features = ["stm32f407"] }
panic-halt = "0.2"

LED 闪烁程序:

#![no_std]
#![no_main]

use cortex_m_rt::entry;
use stm32f4xx_hal::{pac, prelude::*};

#[entry]
fn main() -> ! {
    let dp = pac::Peripherals::take().unwrap();
    let gpioa = dp.GPIOA.split();
    let mut led = gpioa.pa5.into_push_pull_output();

    let rcc = dp.RCC.constrain();
    let clocks = rcc.cfgr.sysclk(48.MHz()).freeze();

    let mut delay = dp.TIM1.delay_us(&clocks);

    loop {
        led.set_high();
        delay.delay_ms(500_u32);
        led.set_low();
        delay.delay_ms(500_u32);
    }
}

嵌入式 Rust 的生态正在快速发展。对于中断处理,我们使用 cortex-m-rt#[interrupt] 宏;对于异步操作,embassy 框架提供了基于 executors 的异步运行时,可以在极低内存占用下实现高效的并发。在我们的项目中,使用 Embassy 后,同样的功能代码量减少了 40%,RAM 占用从 32KB 降到了 18KB。