99·跨平台高级

no_std 嵌入式 Rust

no_std 嵌入式 Rust

学习目标

  1. 理解 no_std 环境
  2. 掌握嵌入式开发基础
  3. 了解 embedded-hal 生态

核心概念

基本 no_std

#![no_std]
#![no_main]

use core::panic::PanicInfo;

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

#[no_mangle]
pub extern "C" fn _start() -> ! {
    // 入口点
    loop {}
}

可用库

[dependencies]
# 核心库(不需要分配器)
nb = "1"                    # 非阻塞 API
embedded-hal = "0.2"        # 硬件抽象层
cortex-m = "0.7"            # ARM Cortex-M
cortex-m-rt = "0.7"         # 运行时
panic-halt = "0.2"          # panic 时停机

embedded-hal trait

use embedded_hal::digital::v2::OutputPin;

struct Led<PIN: OutputPin> {
    pin: PIN,
}

impl<PIN: OutputPin> Led<PIN> {
    fn on(&mut self) {
        self.pin.set_high().ok();
    }

    fn off(&mut self) {
        self.pin.set_low().ok();
    }

    fn toggle(&mut self) {
        // 读取当前状态并翻转
    }
}

分配器(可选)

[dependencies]
alloc-cortex-m = "0.4"  # 嵌入式分配器
#![feature(alloc_error_handler)]

extern crate alloc;
use alloc_cortex_m::CortexMHeap;

#[global_allocator]
static ALLOCATOR: CortexMHeap = CortexMHeap::empty();

#[alloc_error_handler]
fn oom(_: core::alloc::Layout) -> ! {
    loop {}
}

构建

# 添加目标
rustup target add thumbv7em-none-eabihf

# 构建
cargo build --target thumbv7em-none-eabihf --release

小结

概念说明
#![no_std]不使用标准库
#![no_main]自定义入口点
#[panic_handler]必须实现
embedded-hal硬件抽象 trait
cortex-mARM Cortex-M 支持

练习编辑器

rust
Loading...