no_std 嵌入式 Rust
学习目标
- 理解
no_std 环境
- 掌握嵌入式开发基础
- 了解 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"
embedded-hal = "0.2"
cortex-m = "0.7"
cortex-m-rt = "0.7"
panic-halt = "0.2"
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-m | ARM Cortex-M 支持 |