文章标题:从零开始的嵌入式 Rust
正文: 我最近拿到了一块小型微控制器,我觉得这是一个很好的机会,可以更深入地学习基于 ARM 的微控制器的基础知识,以及如何为它们编写 Rust 代码。
在这篇文章中,我将介绍如何在不依赖任何第三方方案的情况下为微控制器创建一个 Rust 应用程序。我会尽量不假设读者具备任何微控制器或 Rust 的先备知识,所以即使你不熟悉它们,我也希望你能跟上(尽管本文不会教你 Rust)。
本文中的所有代码都可以在这个仓库中找到,许多代码块都包含指向相应文件特定修订版本的直接链接。
了解你的目标
首先,我们需要知道我们面向的是什么样的硬件。就我而言,我有一块 Microchip PIC32CM PL10 Curiosity Nano 评估套件,其中包括 PIC32CM6408PL10048 微控制器、一个“Nano Debugger”USB 接口(用于供电以及访问微控制器的调试端口和串口)、一个 LED、一个按钮和一个电容触摸按钮。

微控制器是关注的重点。关于它,我们首先需要知道的是它的指令集架构(ISA)。ISA 定义了微控制器 CPU 能够运行哪些指令,以及这些指令在机器码中如何编码和组织。
当我们将 Rust 或 C 代码编译为二进制时,它会编译成特定的 ISA。不同的 CPU 实现可能使用不同的微架构,甚至可能在基线 ISA 之上包含额外的指令和扩展,但同一个二进制文件在它们上面都能运行。
如今大多数桌面和服务器计算机使用 x86-64 ISA,或者更具体地说,是基线的某个扩展。我们的微控制器基于 ARM:它包含 CPU 核心实现 ARM Cortex-M0+,该核心使用 ARMv6-M 指令集架构(这是 ARM 定义的众多 ISA 之一)。
除了 ISA 之外,这个核心实现还规定了一些内存映射的核心外设(如中断控制器和定时器),而微控制器整体还规定了许多其他外设(GPIO 控制器、更多定时器、串行接口等)。
将代码编译到 ARMv6-M
默认情况下,Rust 编译器为它当前运行所在的平台相同的 ISA 构建。要告诉编译器为另一个 ISA 构建,我们需要向它传递一个目标元组(历史上称为目标三元组)。目标元组不仅指定 ISA,还指定整个平台(包括调用约定、二进制接口、系统库等)。例如,Windows 和 GNU/Linux 可能运行在相同的 ISA 上,但它们由不同的目标元组标识(x86_64-pc-windows-msvc 与 x86_64-unknown-linux-gnu)。
对于 ARMv6-M,我们将使用目标元组 thumbv6m-none-eabi,它面向裸机上的 ARMv6-M ISA,其上没有特定平台。我们可以使用 --target 选项告诉 rustc 或 cargo 我们想要编译到的目标元组。
让我们从设置一个最小的 cargo 项目开始:
$ cargo init --bin ./embedded-rust-from-scratch
#![no_std]
#![no_main]
use core::panic::PanicInfo;
#[panic_handler]
fn panic_handler(_: &PanicInfo) -> ! {
loop {}
}
#[unsafe(no_mangle)]
fn _start() {
loop {}
}
默认情况下,Rust 程序包含 Rust 标准库(std),其中包含用于文件 IO、查询时间、生成进程等的抽象。我们使用的目标本身不支持这些功能,因此标准库不可用,我们需要在 main.rs 顶部用 #![no_std] 属性显式禁用它。我们改为只使用 core 库。main 函数也依赖于标准库,所以我们也需要用 #![no_main] 禁用它。
文章标题:Embedded Rust from Scratch
正文: 我们不再使用 main,而是声明一个名为 _start 的函数,并加上 unsafe 属性 no_mangle,使生成的二进制文件带有 _start 符号,链接器会把它用作程序的入口点1。
链接器入口点只有在生成的二进制文件由操作系统执行时才会用到。在我们的场景里其实并不需要,我加上它只是为了避开一条链接警告。
Rust 还需要一个 panic_handler,当 panic! 宏运行时(相当于 Rust 中的运行时异常)会被调用。
然后我们就可以把 Rust 程序编译到 ARMv6-M。首先需要用 rustup 安装目标平台,然后把 --target 传给 cargo build。
$ rustup target add thumbv6m-none-eabi
$ cargo build --target thumbv6m-none-eabi
这样我们应该就能在 target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch 得到一个 ELF 文件!我们可以用 readelf 和 objdump 检查这个文件是否为我们的目标平台正确生成。
首先用 readelf,用 h 查看 ELF 头,用 A 解析架构相关的段:
$ readelf -hA target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch
ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: ARM
Version: 0x1
Entry point address: 0x200e5
Start of program headers: 52 (bytes into file)
Start of section headers: 3512 (bytes into file)
Flags: 0x5000200, Version5 EABI, soft-float ABI
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 5
Size of section headers: 40 (bytes)
Number of section headers: 15
Section header string table index: 13
Attribute Section: aeabi
File Attributes
Tag_conformance: "2.09"
Tag_CPU_arch: v6S-M
Tag_CPU_arch_profile: Microcontroller
Tag_ARM_ISA_use: No
Tag_THUMB_ISA_use: Thumb-1
Tag_ABI_PCS_R9_use: V6
Tag_ABI_PCS_GOT_use: direct
Tag_ABI_PCS_wchar_t: 4
Tag_ABI_FP_denormal: Needed
Tag_ABI_FP_exceptions: Needed
Tag_ABI_FP_number_model: IEEE 754
Tag_ABI_align_needed: 8-byte
Tag_ABI_align_preserved: 8-byte, except leaf SP
Tag_ABI_optimization_goals: Prefer Debug
Tag_CPU_unaligned_access: None
Tag_ABI_FP_16bit_format: IEEE 754
在 ELF 头里我们看到 Machine: ARM,在 ARM 属性段里我们看到 Tag_CPU_arch: v6S-M,指的是 ARMv6-M ISA。
要使用 objdump,我们需要一个编译时支持该架构的版本。获取它最简单的方法是安装 llvm-tools 这个 rustup 组件(它包含支持 Rust 所支持的全部目标的工具),并通过 cargo-binutils 使用它们:
$ rustup component add llvm-tools
$ cargo install cargo-binutils
然后我们就可以,比如,检查为 _start 函数生成的机器码:
$ cargo objdump --target thumbv6m-none-eabi -- --disassemble=_start
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.01s
embedded-rust-from-scratch: file format elf32-littlearm
Disassembly of section .text:
000200e4 <_start>:
200e4: b580 push {r7, lr}
200e6: af00 add r7, sp, #0x0
200e8: e7ff b 0x200ea <_start+0x6> @ imm = #-0x2
200ea: e7fe b 0x200ea <_start+0x6> @ imm = #-0x4
可以看到我们的函数有四条 16 位 ARM Thumb 指令。这些指令把帧指针(r7)和链接寄存器(lr)保存到栈上,把帧指针更新为新的帧,然后跳进循环,这个循环只是无限地跳回自身2。
文章标题:Embedded Rust from Scratch
正文: 如果我们使用优化编译(cargo build --release --target=...),两个跳转将合并为一个,帧指针的更新应该会被省略(尽管在 Rust 1.100,也就是本文使用的版本中,rustc 在 Thumb 目标上从不省略帧指针)。
好了,我们构建了一个包含一些代码的 ELF 文件。但这还不足以将其烧录到微控制器上,更不用说运行它了。
要使其可烧录,我们需要明确二进制数据和运行时数据将映射到内存中的具体位置,以便链接后任何跳转、加载及类似指令都指向正确的内存地址,并向编程工具指明内容应写入微控制器闪存的哪个位置。
配置链接器
首先,让我们配置 cargo 项目,使其默认构建到我们期望的目标,而无需每次都传递 --target。我们稍后还会使用这个文件来指定额外的参数。
我们添加一个 .cargo/config.toml 文件,指定 build.target 选项:
[build]
target = "thumbv6m-none-eabi"
现在,为了告诉链接器代码、静态数据和运行时数据应存储在何处并映射到哪里,我们需要创建一个链接器脚本。
rustc 首先将代码编译为具有可重定位代码的目标文件,这意味着指令引用的所有地址都只是虚拟地址,之后它会调用链接器程序(对于此目标,默认是 lld)将它们合并为单个可执行文件,其中所有代码被放置到内存的不同部分,所有指令地址都被解析3。
实际上,在大多数通用操作系统上,代码并不会映射到特定地址。相反,编译器生成位置无关代码,链接器生成位置无关可执行文件,可以在任意地址加载。然后动态加载器在每次程序加载到内存时应用重定位。操作系统还利用它来实现地址空间布局随机化(ASLR),以缓解某些漏洞利用。但这些都不适用于我们这里所针对的这类微控制器。
中间目标文件和最终可执行文件都以段(section)来组织其内容,可执行文件还会将这些段映射到内存段(segment)。之后,编程工具会解析这些信息,以确定应将其写入闪存的哪个位置。
为了探索这一点,让我们先把 Rust 程序变得稍微有趣一些:
#![no_std]
#![no_main]
use core::panic::PanicInfo;
#[used]
#[unsafe(no_mangle)]
static mut ZEROS: [u8; 256] = [0; 256];
#[used]
#[unsafe(no_mangle)]
static mut STRING_PTR: &str = "This is a string";
#[panic_handler]
fn panic_handler(_: &PanicInfo) -> ! {
loop {}
}
#[unsafe(no_mangle)]
fn _start() {
loop {}
}
这里我只是添加了一个完全由零组成的可变静态缓冲区,以及一个可变静态字符串引用,它是指向只读字符串的指针。我用 #[used] 属性标记它们,这样它们就不会被编译器和链接器作为未使用项丢弃。
然后我们可以编译新的可执行文件,并使用 readelf -Sls(S 显示段,l 显示程序头/内存段,s 显示符号)来查看链接器如何布局这些段:
$ readelf -Sls target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch
There are 18 section headers, starting at offset 0xea8:
文章标题:从零开始学嵌入式 Rust
正文:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .ARM.exidx ARM_EXIDX 000100f4 0000f4 000010 00 AL 3 0 4
[ 2] .rodata PROGBITS 00010104 000104 000010 10 AM 0 0 1
[ 3] .text PROGBITS 00020114 000114 000008 00 AX 0 0 2
[ 4] .data PROGBITS 0003011c 00011c 000008 00 WAR 0 0 4
[ 5] .bss NOBITS 00030124 000124 000100 00 WAR 0 0 1
[ 6] .debug_abbrev PROGBITS 00000000 000124 00013f 00 0 0 1
[ 7] .debug_info PROGBITS 00000000 000263 0004a8 00 0 0 1
[ 8] .debug_aranges PROGBITS 00000000 00070b 000038 00 0 0 1
[ 9] .debug_ranges PROGBITS 00000000 000743 000018 00 0 0 1
[10] .debug_str PROGBITS 00000000 00075b 00049e 01 MS 0 0 1
[11] .comment PROGBITS 00000000 000bf9 00008c 01 MS 0 0 1
[12] .ARM.attributes ARM_ATTRIBUTES 00000000 000c85 000034 00 0 0 1
[13] .debug_frame PROGBITS 00000000 000cbc 00004c 00 0 0 4
[14] .debug_line PROGBITS 00000000 000d08 000053 00 0 0 1
[15] .symtab SYMTAB 00000000 000d5c 000060 10 17 3 4
[16] .shstrtab STRTAB 00000000 000dbc 0000b3 00 0 0 1
[17] .strtab STRTAB 00000000 000e6f 000036 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
L (link order), O (extra OS processing required), G (group), T (TLS),
C (compressed), x (unknown), o (OS specific), E (exclude),
R (retain), D (mbind), y (purecode), p (processor specific)
Elf file type is EXEC(Executable file)
Entry point 0x20115
There are 6 program headers, starting at offset 52
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
PHDR 0x000034 0x00010034 0x00010034 0x000c0 0x000c0 R 0x4
LOAD 0x000000 0x00010000 0x00010000 0x00114 0x00114 R 0x10000
LOAD 0x000114 0x00020114 0x00020114 0x00008 0x00008 R E 0x10000
LOAD 0x00011c 0x0003011c 0x0003011c 0x00008 0x00108 RW 0x10000
GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0
ARM_EXIDX 0x0000f4 0x000100f4 0x000100f4 0x00010 0x00010 R 0x4
Section to Segment mapping:
Segment Sections...
00
01 .ARM.exidx .rodata
02 .text
03 .data .bss
04
05 .ARM.exidx
Symbol table '.symtab' contains 6 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS d5qcrjykt479b5r4[...]
2: 00020114 0 NOTYPE LOCAL DEFAULT 3 $t
3: 0003011c 8 OBJECT GLOBAL DEFAULT 4 STRING_PTR
4: 00030124 256 OBJECT GLOBAL DEFAULT 5 ZEROS
5: 00020115 8 FUNC GLOBAL DEFAULT 3 _start
这里有很多 section,但其中大多数只是存储元数据或调试信息。真正被加载到内存中的 section 有 5 个,它们被标记为 A(alloc)标志,并被映射到程序头中的 3 个 LOAD 段之一。
.text section 存储程序的真正机器码。从符号表可以看到,符号 _start 位于地址 0x00020115,它位于 .text section 内部,而该 section 从地址 0x000201144 开始。
_start 与 .text 的地址只相差一,是因为函数指针的最低有效位被置为 1,以表示它是指向 Thumb 状态函数的指针。_start 的第一条指令仍然从 0x00020114 开始,因为指令总是从偶地址开始。ARMv6-M 只支持 Thumb,但有些 ARM 架构同时支持 Thumb 状态和 ARM 状态指令,这一位正是用来表示这一点的。
文章标题:Embedded Rust from Scratch
正文: .rodata 段存储只读数据。在我们的例子中,它的大小是 0x10,正好对应我们的 16 字符字符串。
.data 段存储可修改数据,在我们的例子中就是字符串的指针(4 字节)和长度(4 字节),所以大小是 0x08。
.bss 段表示零初始化的可修改数据。该段的内容实际上并不存储在 ELF 文件中(由段类型 NOBITS 指示),它只是向操作系统或运行时表明需要分配/初始化零值内存。它的长度是 0x100,对应我们的 256 字节缓冲区 ZEROS。
此外还有 .ARM.exidx,它存储展开信息,例如在 panic! 执行期间用于展开栈帧。Rust 默认不支持在该目标上展开,因此我们不会使用这个段。
在各段之后,是一个程序头列表,它描述了操作系统实际应如何将各个段(以及其中的节)加载到内存中,或者在我们的情况中,是编程工具如何将它们加载到 flash 中。
目前这些段只是被映射到 0x00010000、0x00020000 等地址附近。我们需要让它们指向我们微控制器的实际内存映射。
如果我们打开 PIC32CM6408PL10048 的数据手册,在第 4.3 节 Product Mapping 中可以看到,内部 Flash 有 64 KiB,起始于 0x0C000000,高速 SRAM 有 8 KiB,位于地址 0x20000000。
要把这些信息传给 lld(以及任何其他兼容 GNU ld 的链接器),我们需要编写如下链接器脚本:
/* We declare our two memory regions */
MEMORY {
/* FLASH is readable and executable */
FLASH (rx) : ORIGIN = 0x0C000000, LENGTH = 64K
/* ram is readable and writable */
SRAM (rw) : ORIGIN = 0x20000000, LENGTH = 8K
}
/* then we declare our output sections, what input sections they should contain,
* and where they should be located in memory. */
SECTIONS {
/* map all executable and read-only sections to FLASH */
.text : {
*(.text)
*(.text.*)
} > FLASH
.rodata : {
*(.rodata)
*(.rodata.*)
} > FLASH
.ARM.exidx : {
*(.ARM.exidx)
} > FLASH
/* map zero-initialized data to SRAM */
.bss : {
*(.bss)
*(.bss.*)
} > SRAM
/* map initialized ram data to SRAM, but stored in FLASH */
.data : {
*(.data)
*(.data.*)
} > SRAM AT> FLASH
}
在脚本中,我们声明了两个内存区域,声明了输出段以及它们应位于何处。要了解更多关于链接器脚本工作原理的内容,我推荐 mcyoung 的这篇文章,以及 ld 文档中的详细信息。
然后我们配置 cargo,向 rustc 传递一个额外选项,使 rustc 向链接器传递一个标志,告诉它使用我们的链接器脚本:
[build]
target = "thumbv6m-none-eabi"
[target.thumbv6m-none-eabi]
rustflags = [
"-C", "link-arg=-Tlinker.ld",
]
运行 cargo clean && cargo build5,然后再次检查生成的 ELF 文件:
cargo 不会检测链接器脚本本身的更改,所以请运行 cargo clean 以确保生效。
$ readelf -Sls target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch
There are 18 section headers, starting at offset 0x20e8c:
文章标题:Embedded Rust from Scratch
正文:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .text PROGBITS 0c000000 010000 000008 00 AX 0 0 2
[ 2] .rodata PROGBITS 0c000008 010008 000010 10 AM 0 0 1
[ 3] .ARM.exidx ARM_EXIDX 0c000018 010018 000010 00 AL 1 0 4
[ 4] .bss NOBITS 20000000 020000 000100 00 WAR 0 0 1
[ 5] .data PROGBITS 20000100 020100 000008 00 WAR 0 0 4
[ 6] .debug_abbrev PROGBITS 00000000 020108 00013f 00 0 0 1
[ 7] .debug_info PROGBITS 00000000 020247 0004a8 00 0 0 1
[ 8] .debug_aranges PROGBITS 00000000 0206ef 000038 00 0 0 1
[ 9] .debug_ranges PROGBITS 00000000 020727 000018 00 0 0 1
[10] .debug_str PROGBITS 00000000 02073f 00049e 01 MS 0 0 1
[11] .comment PROGBITS 00000000 020bdd 00008c 01 MS 0 0 1
[12] .ARM.attributes ARM_ATTRIBUTES 00000000 020c69 000034 00 0 0 1
[13] .debug_frame PROGBITS 00000000 020ca0 00004c 00 0 0 4
[14] .debug_line PROGBITS 00000000 020cec 000053 00 0 0 1
[15] .symtab SYMTAB 00000000 020d40 000060 10 17 3 4
[16] .shstrtab STRTAB 00000000 020da0 0000b3 00 0 0 1
[17] .strtab STRTAB 00000000 020e53 000036 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
L (link order), O (extra OS processing required), G (group), T (TLS),
C (compressed), x (unknown), o (OS specific), E (exclude),
R (retain), D (mbind), y (purecode), p (processor specific)
Elf file type is EXEC (Executable file)
Entry point 0xc000001
There are 6 program headers, starting at offset 52
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
LOAD 0x010000 0x0c000000 0x0c000000 0x00008 0x00008 R E 0x10000
LOAD 0x010008 0x0c000008 0x0c000008 0x00020 0x00020 R 0x10000
LOAD 0x020000 0x20000000 0x20000000 0x00000 0x00100 RW 0x10000
LOAD 0x020100 0x20000100 0x0c000028 0x00008 0x00008 RW 0x10000
GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0
ARM_EXIDX 0x010018 0x0c000018 0x0c000018 0x00010 0x00010 R 0x4
Section to Segment mapping:
Segment Sections...
00 .text
01 .rodata .ARM.exidx
02 .bss
03 .data
04
05 .ARM.exidx
Symbol table '.symtab' contains 6 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS d5qcrjykt479b5r4[...]
2: 0c000000 0 NOTYPE LOCAL DEFAULT 1 $t
3: 20000100 8 OBJECT GLOBAL DEFAULT 5 STRING_PTR
4: 20000000 256 OBJECT GLOBAL DEFAULT 4 ZEROS
5: 0c000001 8 FUNC GLOBAL DEFAULT 1 _start
现在可以看到,.text 位于地址 0x0C000000,.rodata 位于 0x0C000008,.bss 位于 0x20000000,.data 位于 0x20000100,与我们的预期一致。
值得注意的是段 03(最后一个 LOAD 段)的 VirtAddr 和 PhysAddr 两列,.data 段正是被映射到那里。VirtAddr 表示虚拟内存地址,PhysAddr 表示物理内存地址,或者按链接器的叫法称为加载内存地址(LMA)。它们分别指明该段在运行时所在的位置,以及它从哪里被加载。
以 .data 为例,它的虚拟地址位于 RAM 中,为 0x20000100,但它的数据实际上存储在 FLASH 中,为 0x0C000028。
总之,既然一切都已经正确地放置到内存中,我们已经有能力把它烧录进微控制器了!但要让代码真正运行起来,我们还需要设置一些东西。
运行时初始化
文章标题:从零开始学习嵌入式 Rust
我们首先需要知道的是 CPU 将从何处开始执行代码。对于基于 ARM Cortex-M 的微控制器,初始栈指针(SP)和初始程序计数器(PC)是从向量表中读取的,而向量表是相对于向量表偏移寄存器 VTOR 读取的(参见 ARMv6-M 架构参考手册的 B1.5.5 节)。向量表还包含微控制器所支持的每个异常处理程序的函数指针,例如 Reset(同时也是初始 PC)、HardFault 等,以及每个外部中断的函数指针(参见手册的 B1.5.3 节)。
具体到 PIC32CM6408PL10048,在复位时它会从 Boot ROM 内存中运行一些初始化代码(参见数据手册的 6.4.1 节和 6.5.4.5 节),之后将 VTOR 设置为 FLASH 的起始地址,并从那里的向量表加载初始 SP 和 PC。它还保留了 32 个外部中断。
所以,我们的二进制文件需要有一个向量表,正确填充并定位在 flash 的起始处。我们可以更新链接脚本来实现这一点:
/* 然后我们声明输出段,它们应包含哪些输入段,
* 以及它们应位于内存中的何处。 */
SECTIONS {
/* 在 FLASH 起始处定义 .vector_table */
.vector_table ORIGIN(FLASH) : {
/* 初始栈指针。
* 从 SRAM 末尾开始(栈向下增长时 SP 递减) */
LONG(ORIGIN(SRAM) + LENGTH(SRAM))
/* 初始程序计数器和 `Reset` 异常处理程序。
* 指向 `_start` 函数 */
LONG(_start)
/* 目前用 0 填充向量表的其余部分。此微控制器
* 在 15 个默认异常之外保留了 32 个外部中断 */
FILL(0x00)
. += 4 * (15 - 1 + 32);
}
/* ... */
}
如果我们重新构建 ELF 文件并用 readelf 检查它(使用 -x .vector_table 转储其内容):
$ readelf -Ss -x .vector_table target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch
There are 19 section headers, starting at offset 0x20e98:
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .vector_table PROGBITS 0c000000 010000 0000c0 00 A 0 0 1
[ 2] .text PROGBITS 0c0000c0 0100c0 000008 00 AX 0 0 2
[ 3] .rodata PROGBITS 0c0000c8 0100c8 000010 10 AM 0 0 1
[ 4] .ARM.exidx ARM_EXIDX 0c0000d8 0100d8 000010 00 AL 2 0 4
[ 5] .bss NOBITS 20000000 020000 000100 00 WAR 0 0 1
[ 6] .data PROGBITS 20000100 020100 000008 00 WAR 0 0 4
[ 7] .debug_abbrev PROGBITS 00000000 020108 00013f 00 0 0 1
[ 8] .debug_info PROGBITS 00000000 020247 0004a8 00 0 0 1
[ 9] .debug_aranges PROGBITS 00000000 0206ef 000038 00 0 0 1
[10] .debug_ranges PROGBITS 00000000 020727 000018 00 0 0 1
[11] .debug_str PROGBITS 00000000 02073f 00049e 01 MS 0 0 1
[12] .comment PROGBITS 00000000 020bdd 00008c 01 MS 0 0 1
[13] .ARM.attributes ARM_ATTRIBUTES 00000000 020c69 000034 00 0 0 1
[14] .debug_frame PROGBITS 00000000 020ca0 00004c 00 0 0 4
[15] .debug_line PROGBITS 00000000 020cec 000053 00 0 0 1
[16] .symtab SYMTAB 00000000 020d40 000060 10 18 3 4
[17] .shstrtab STRTAB 00000000 020da0 0000c1 00 0 0 1
[18] .strtab STRTAB 00000000 020e61 000036 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
L (link order), O (extra OS processing required), G (group), T (TLS),
C (compressed), x (unknown), o (OS specific), E (exclude),
R (retain), D (mbind), y (purecode), p (processor specific)
符号表 '.symtab' 包含 6 个条目: Num: Value Size Type Bind Vis Ndx Name 0: 00000000 0 NOTYPE LOCAL DEFAULT UND 1: 00000000 0 FILE LOCAL DEFAULT ABS d5qcrjykt479b5r4[...] 2: 0c0000c0 0 NOTYPE LOCAL DEFAULT 2 $t 3: 20000100 8 OBJECT GLOBAL DEFAULT 6 STRING_PTR 4: 20000000 256 OBJECT GLOBAL DEFAULT 5 ZEROS 5: 0c0000c1 8 FUNC GLOBAL DEFAULT 2 _start
节区 '.vector_table' 的十六进制转储: 0x0c000000 00200020 c100000c 00000000 00000000 . . ............ 0x0c000010 00000000 00000000 00000000 00000000 ................ 0x0c000020 00000000 00000000 00000000 00000000 ................ 0x0c000030 00000000 00000000 00000000 00000000 ................ 0x0c000040 00000000 00000000 00000000 00000000 ................ 0x0c000050 00000000 00000000 00000000 00000000 ................ 0x0c000060 00000000 00000000 00000000 00000000 ................ 0x0c000070 00000000 00000000 00000000 00000000 ................ 0x0c000080 00000000 00000000 00000000 00000000 ................ 0x0c000090 00000000 00000000 00000000 00000000 ................ 0x0c0000a0 00000000 00000000 00000000 00000000 ................ 0x0c0000b0 00000000 00000000 00000000 00000000 ................
我们可以看到 .vector_table 位于 0x0c000000,它的十六进制转储包含 0x20002000 和 0x0c0000c1(由于小端序,字节是反的),它们分别是 SRAM 的末尾和 _start 符号的值。
我们需要做的最后一件事是一些运行时初始化。像 C 和 Rust 这样的高级语言需要最小运行时才能让代码工作,这通常由操作系统、系统库、标准库等提供。我们这里没有这些,所以需要自己实现。幸运的是,对于我们正在做的事情,只需按照 .bss 和 .data 节区所描述的那样初始化 RAM 就足够了。
因为任何 Rust 代码都已经假设其运行时已初始化,所以我们不能用它来初始化运行时。其他高级语言也是如此。我们需要改用汇编代码。幸运的是,我们可以通过 core::arch::asm! 和 core::arch::global_asm! 在 Rust 本身中编写汇编。
首先,我们需要更新链接器脚本,声明一些标记每个节区起始和结束的符号。我还将使用 load(ldr)和 store(str)指令以 4 字节块初始化节区,而这些指令只允许对齐地址,所以我们还需要确保这些节区按 4 字节对齐。
链接器脚本随后变为:
SECTIONS { / map zero-initialized data to SRAM, 4-byte aligned / .bss : ALIGN(4) { (.bss) (.bss.) / also align the end address of the section */ . = ALIGN(4); } > SRAM
/ map initialized ram data to SRAM, but stored in FLASH, 4-byte aligned / .data : ALIGN(4) { (.data) (.data.) / also align the end address of the section */ . = ALIGN(4); } > SRAM AT> FLASH
/ ... / }
/ declare symbols for initializing SRAM at runtime / bss_start = ADDR(.bss); bss_end = bss_start + SIZEOF(.bss);
data_start = ADDR(.data); data_end = data_start + SIZEOF(.data);
load_data_start = LOADADDR(.data);
然后我们用以下 global_asm! 调用替换现有的 fn _start() 函数:
core::arch::global_asm! { r#" / Declare _start label as an externally visible symbol / .global _start
/ specifies that the symbol _start points to a thumb instruction / .thumb_func
/ our _start routine / _start:
/ zero .bss section / .Lzero_bss: / load a value 0 and pointers to the start and end of bss in registers / movs r0, #0 ldr r1, =bss_start ldr r2, =bss_end
.Lzero_bss_loop: / if r1 is at bss_end, stop the loop and proceed to copy .data / cmp r1, r2 bcs .Lcopy_data
/ 将 32 位 0 存储到 r1 地址处 / str r0, [r1] / r1 加 4,然后循环 / adds r1, #4 b .Lzero_bss_loop
/ 将 .data 从加载地址复制到 RAM / .Lcopy_data: / 加载指向 FLASH 和 RAM 中 .data 起始与结束位置的指针 / ldr r0, =load_data_start ldr r1, =data_start ldr r2, =data_end
.Lcopy_data_loop: / 如果 r1 到达 data_end,停止循环并继续调用 main / cmp r1, r2 bcs .Lcall_main
/ 从 r0 地址加载一个 32 位值,并存储到 r1 地址处 / ldr r3, [r0] str r3, [r1] / r0 和 r1 各加 4,然后循环 / adds r0, #4 adds r1, #4 b .Lcopy_data_loop
/ 调用 main 函数。 / .Lcall_main: / main 没有参数,因此无需额外设置 / bl main
/ 如果 main 返回,就进入无限循环 / .Lhang: b .Lhang "# }
#[unsafe(no_mangle)] extern "C" fn main() {}
在上面的代码中,我们用汇编定义了 _start 例程,它会将 .bss 段清零,把 .data 从 FLASH 复制到 SRAM,最后调用 fn main。
我们需要加上 #[unsafe(no_mangle)] 属性,让这个函数生成的名字恰好是 main 的符号,并用 extern "C" 指定它的调用约定。调用约定定义了调用该函数时机器码需要做什么。默认情况下,Rust 函数使用不稳定的调用约定,因此我们改为指定使用 C 调用约定,它在每个目标平台上都是稳定的,这样我们就能知道调用它所需的汇编代码。在这个简单的例子中,只需执行分支并链接(bl)指令即可。
好,现在终于可以在 main 里写一些应用代码了!
#[unsafe(no_mangle)] extern "C" fn main() { // 让我们,呃,计算斐波那契数列吧! let mut a = 1; let mut b = 1; for _ in 0..10 { (a, b) = (b, a + b); } }
……但是,除非你满足于想象 CPU 在做事,否则烧录这种代码和什么都不做差不多。我们需要让微控制器做一些真正看得见的事情。
## 点亮一个 LED
在嵌入式软件开发的世界里,Hello World 程序的等价物就是让 LED 闪烁的程序。你也可以打印 Hello World,但那至少需要先有一个能工作的串口接口。让 LED 闪烁所需的条件要少得多。
我的板子上有一个名为 LED0 的 LED,连接在微控制器的 PB02 引脚和 MCU 电压源之间,串联了一个 1 kΩ 电阻。因此,如果我们将该引脚配置为低电平,LED 应该会导通并发光,而在高电平时熄灭。
为了控制引脚电压电平,这个微控制器有 PORT 外设(见数据手册第 27 节)。它允许配置微控制器每个引脚的行为。
要在这个微控制器上访问该外设,我们需要使用内存映射寄存器,更一般地称为内存映射输入/输出(MMIO)。这类寄存器被映射到地址空间中的特定地址,我们可以像读写其他内存一样读写它们。另一种方式是 CPU 拥有专门用于访问它们的指令。
如果我们再次查看第 4.3 节产品映射,可以看到 PORT 外设被映射到从地址 0x41000000 开始的内存。从第 27.6 节可以看到 PORT 每个寄存器的偏移量。PORT 有两组寄存器,分别称为 A 和 B,每组都有自己独立的一套寄存器,控制各自的一组引脚。
我们可以使用 DIR 寄存器来控制引脚应该是输入(允许读取外部数字信号)还是输出(允许输出驱动电压电平),并用 OUT 来定义它应该驱动什么电压电平。
从引脚名称“PB02”可知,它是第二组 PORT 的第 3 个引脚。因此我们需要访问第二组 PORT 寄存器中 DIR 和 OUT 寄存器的第 2 位。B 组的偏移量为 0x80,DIR 和 OUT 分别位于偏移量 0x00 和 0x10 处,所以我们需要访问 0x41000080 和 0x41000090。
在 Rust 中写法如下:
const DIR01: mut u32 = 0x41000080 as mut u32; const OUT01: mut u32 = 0x41000090 as mut u32;
#[unsafe(no_mangle)] extern "C" fn main() { unsafe { // set PB02 as output DIR01.write_volatile(1 << 2); // set PB02 as level low OUT01.write_volatile(0); } }
我们将每个寄存器的字面地址转换为裸指针,从而创建指向它们的指针,并存入 const 中。然后用 write_volatile 将 DIR01 的第 2 位置为 1,并将 OUT01 的对应位置为 0。这应该能让 LED 点亮。这里必须使用 write_volatile,因为这些写操作会在硬件中产生副作用,否则编译器会认为写操作没有副作用,可能将其优化掉。
另请注意,我们使用的是裸指针,它们不保证有效性,因此在 Rust 中通过它们写入是不安全操作。我们需要把它们包在 unsafe 块中,并手动验证该操作确实正确(换句话说,是 sound 的)。
在 Rust 中,强烈不鼓励使用 unsafe 代码,除非绝对必要。因此,如果每次需要改变引脚输出电平都要用到它,那会非常糟糕。后面我们会探讨如何将这种不安全封装在一个可复用的安全抽象之后。
但现在,我们可以用以下代码让 LED 闪烁:
const DIR01: mut u32 = 0x41000080 as mut u32; const OUT01: mut u32 = 0x41000090 as mut u32;
// Declare the main function the code above calls into. #[unsafe(no_mangle)] extern "C" fn main() { // set PB02 as output unsafe { DIR01.write_volatile(1 << 2); }
let mut toggle: bool = false; loop { toggle = !toggle; // set PB02 output level unsafe { OUT01.write_volatile((toggle as u32) << 2); } delay_1s(); } }
pub fn delay_1s() { // count down 1.3 million times at 4MHz, 3 cycles per iteration, which // equals to 1 second. let count: u32 = 1_333_333; unsafe { core::arch::asm!( "2:", "subs {count}, #1", // 1 cycle "bne 2b", // 2 cycles if taken, 1 otherwise count = inout(reg) count => _, options(nomem, nostack), ); } }
它把 PB02 的方向设为输出,然后每秒在 0 和 1 之间切换输出电平。我还用了一些汇编将一个计数器递减 133 万次,在 4 MHz 的 CPU 时钟频率下,这应该就是 1 秒的延迟6。
4 MHz 是退出启动时的默认时钟频率,但也可以配置到最高 24 MHz,这会影响这段延迟代码。
现在我们终于有了一个值得烧录到设备上的程序!
## Flashing Our Code
烧录方法因设备而异。微控制器可能有启动 ROM 代码,从串行接口或 USB 读取烧录指令,或者可能有专用引脚用于烧录,或者可能直接从外部闪存设备读取代码。
基于 ARM 的微控制器,比如我们的 PIC32CM,通常有专用引脚用于访问其片上调试器(OCD),从而可以调试和烧录设备。我们的微控制器使用 Serial Wire Debug(SWD)接口(由 ARM 定义的标准接口),它由两根线组成:SWDIO(数据)和 SWCLK(时钟)。要使用它,需要将这些信号(加上 GND、VCC 和 RESET)连接到调试探针设备,比如 J-Link。
幸好许多开发套件(包括我的)都内置了调试探针,可为微控制器的调试接口提供 USB 接口。我的板子包含一个 Microchip Nano Debugger 调试探针,它提供 CMSIS-DAP 接口。
CMSIS 是 ARM 定义的一套工具和标准,旨在为所有 ARM 设备提供更一致的支持。CMSIS-DAP 标准定义了与调试探针的通信接口,因此任何兼容的编程工具都应能与任何兼容的调试探针通信。所以有很多工具可以让我们烧录设备,比如 Microchip 自己提供的工具,或者 OpenOCD、pyOCD 和 probe-rs 等开源工具。
不幸的是,尽管调试探针本身遵循标准化协议,但每个微控制器访问其内部闪存的接口各不相同,因此需要不同的闪存算法。所以,工具通常需要为每个微控制器系列提供定制支持。据我所见,上面提到的开源工具都没有内置对 PIC32CM PL10 系列的支持(大多数开发者只是使用厂商提供的工具,而且这是一个今年发布的相对较新的系列,所以我并不意外)。
但幸运的是,ARM 还制定了 CMSIS-Pack 规范,它基本上是一个 zip 文件,用于分发文档、调试序列、闪存算法、设备头文件等,理论上应该提供使用微控制器所需的一切。pyOCD 可以解析这些包来获得对微控制器的支持,所以很多时候它不需要内置支持就能工作。这对烧录我的 PIC32CM6408PL10048 有效,但并非 100% 有效(我没有大量测试,但例如通过 gdb 调试就不起作用)。
我自己为 probe-rs 添加了对我的微控制器的支持,这也是我将在本文中使用的工具。probe-rs 是由嵌入式 Rust 社区开发的调试工具包,与 Rust 的集成更好,所以我觉得在这里使用它很合适。
按照安装说明(我不得不从源码安装才能获得我刚添加的支持)和设置说明操作后,我们可以通过 USB 将设备连接到 PC,并检查它是否被识别:
$ probe-rs list The following debug probes were found: [0]: nEDBG CMSIS-DAP -- 03eb:2175-0:MC020148902AUR006904 (CMSIS-DAP) $ probe-rs info Detected chip: PIC32CM6408PL10048 For more detailed information about the target, run with the --verbose flag.
最后我们可以把程序烧录到设备上:
$ probe-rs download target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch Finished in 2.43s Erasing ✔ 100% [####################] 10.00 KiB @ 9.36 KiB/s (took 1s) Programming ✔ 100% [####################] 10.00 KiB @ 7.96 KiB/s (took 1s)
然后我们可以看到 LED 每秒亮灭一次!
另外,probe-rs 安装了一个 cargo-flash 二进制文件,因此我们可以用一条命令构建并烧录程序:
$ cargo flash Compiling embedded-rust-from-scratch v0.1.0 Finished dev profile [unoptimized + debuginfo] target(s) in 0.74s Finished in 2.42s Erasing ✔ 100% [####################] 10.00 KiB @ 9.38 KiB/s (took 1s) Programming ✔ 100% [####################] 10.00 KiB @ 8.02 KiB/s (took 1s)
## 添加安全抽象
正如我之前提到的,我们正在使用 unsafe 操作来访问 PORT 外设的寄存器。在 Rust 中,如果一个操作带有任何前置条件,而违反这些条件可能会破坏内存安全,或通常导致任何形式的未定义行为,则该操作被视为 unsafe。例如,解引用裸指针的前置条件是该指针有效。
为了更安全,我们可以把 unsafe 操作封装进一个函数里。这个函数随后可以利用额外的检查或类型系统来确保 unsafe 操作的前置条件得到满足,从而被视为安全的。但如果该函数没有确保所有前置条件,那么它就被视为 unsafe,应当如此标记,最好还附带文档说明必须满足哪些条件才能安全地调用它。
对于我们的应用,我们可以创建一个函数来打开或关闭 LED,例如:
/// Set LED0 On or Off. /// /// # Safety /// /// This function is only valid to call if a concurrent /// access to DIR01 and OUT01 is not possible. unsafe fn set_led0(on: bool) { unsafe { let dir = DIR01.read_volatile(); DIR01.write_volatile(dir | (1 << 2));
let mut out = OUT01.read_volatile(); // LED0 turns on when the pin output is low. if on { out &= !(1 << 2); } else { out |= 1 << 2; } OUT01.write_volatile(out); } }
这个函数读取 DIR 和 OUT 的当前值,更新与我们的 LED 对应的位,然后把值写回去。这样我们的 main 函数就变成了:
#[unsafe(no_mangle)] extern "C" fn main() { let mut toggle: bool = false; loop { toggle = !toggle; unsafe { set_led0(toggle); } delay_1s(); } }
注意这个函数仍然是 unsafe7 的,因为它对那些寄存器8 执行了非原子操作。如果另一段代码在读取与其对应的写入之间并发运行(在这里就是中断),并且那段代码更新了寄存器的另一位,那么当写入执行时,那次更新就会被丢弃。
这个函数不一定是 unsafe 的。这段代码特定于我们的微控制器,在这里执行的读写是原子的,因此没有违反 Rust 的内存安全,因为竞态条件本身并不被视为 unsafe(参见 Data Races and Race Conditions)。但这种竞态可能导致另一段 unsafe 代码所依赖的某些安全不变量不再成立,在这种情况下该函数就是 unsound 的,而这个竞态可以被视为数据竞态。
这块 PIC32 还有 DIRSET、OUTCLR、OUTSET 等寄存器,可以用它们来实现这个函数而无需进行读-改-写这种非原子操作,但为了示例起见我选择了这种实现。
这将会是一个数据竞态。而 Rust 正是为了让这类 bug 不可能发生而构建的。这里的主要问题在于 PORT 寄存器是全局可访问的,因此我们需要一种方式来协调对它们的访问,使其永远不会被并发执行。如果我们做到了这一点,就可以去掉函数上的 unsafe 标记,使该函数的所有调用者都变得安全。
我们可以引入一个使用 Mutex 锁之类的运行时检查,但我们可以做得更好。我们可以利用 Rust 的类型系统让 PORT 不再全局可访问,然后使用通常的 Rust 借用机制使每次访问都安全,且零运行时开销。首先我们在一个名为 port 的新模块中创建一个类型 PORT,用来表示我们的外设:
/// Interface for the PORT Peripheral. pub struct PORT(());
struct PORT(()) 是一个元组结构体,包含一个类型为 () 的私有字段,即单元类型。字段类型并不重要,重要的是它的字段是私有的,因此该类型无法在此模块之外被构造。
然后我们添加一个用于创建该类型的公共方法:
pub struct PORT(()); impl PORT { /// Create a new PORT. /// /// # Safety /// /// This method should only be called if no other instance of PORT /// exists. pub unsafe fn steal() -> Self { Self(()) } }
然后我们把之前那个 unsafe 函数更新为:
/// SAFETY: 仅在持有 &mut PORT 时才可访问。 const DIR01: mut u32 = 0x41000080 as mut u32; /// SAFETY: 仅在持有 &mut PORT 时才可访问。 const OUT01: mut u32 = 0x41000090 as mut u32;
/// 将 LED0 打开或关闭。 fn set_led0(_port: &mut PORT, on: bool) { // SAFETY: 我们拥有对 PORT 的独占引用, // 因此访问 PORT 寄存器是安全的。 unsafe { let dir = DIR01.read_volatile(); DIR01.write_volatile(dir | (1 << 2));
let mut out = OUT01.read_volatile(); // LED0 在引脚输出为低电平时点亮。 if on { out &= !(1 << 2); } else { out |= 1 << 2; } OUT01.write_volatile(out); } }
PORT 类型的设计保证同一时刻只存在它的一个实例。这一性质应由调用 PORT::steal() 的代码来保证,因此该函数是 unsafe 的。
随后 set_led0 接收一个 &mut PORT。在 Rust 中,&mut PORT 表示对 PORT 的独占引用,这意味着 Rust 在其语言语义上保证了 set_led0 是唯一持有 PORT 单个实例活动引用的函数,因此访问 DIR01 和 OUT01 是完全可靠的,因为任何其他执行上下文(例如中断处理程序)都不可能同时持有对 PORT 的引用。
于是 main 变成:
mod port; use crate::port::PORT;
// 声明上面代码所调用的 main 函数。 #[unsafe(no_mangle)] extern "C" fn main() { // SAFETY: 仅在此时调用 PORT::steal()。 let mut port = unsafe { PORT::steal() };
let mut toggle: bool = false; loop { toggle = !toggle; set_led0(&mut port, toggle); delay_1s(); } }
我们的应用只需使用一次 unsafe 来获得 PORT 的一个实例,之后对其寄存器的所有访问都是安全的!
## 更完整的 PORT 抽象
当然,之前的代码非常刻意,你永远不会只为单个引脚暴露一个安全抽象。自然的做法是构建一个为整个 PORT 外设建模的抽象。
首先我们可以声明一些结构体来表示寄存器块:
#[repr(C)] struct PORTRegisterBlock { groups: [PORTGroupRegisterBlock; 2], }
#[repr(C, align(0x80))] struct PORTGroupRegisterBlock { dir: u32, dirclr: u32, dirset: u32, dirtgl: u32, out: u32, outclr: u32, outset: u32, outtgl: u32, r#in: u32, ctrl: u32, wrconfig: u32, evctrl: u32, pmux: [u8; 16], pincfg: [u8; 32], }
注意我们使用了 repr(C) 和 repr(C, align(0x80)) 属性,以确保字段在内存中的布局与真实硬件外设中寄存器的精确偏移一致。如果没有 repr(C),Rust 可以为了优化结构体布局(或出于任何其他原因)而重排字段。
然后我们用方法和类型来更新我们的 PORT 类型,为 PORT 外设提供安全且便捷的抽象。
#[derive(Clone, Copy)] pub enum PortDirection { Input, Output, }
#[derive(Clone, Copy)] pub enum PortGroup { A = 0, B = 1, }
#[derive(Clone, Copy)] pub struct PortPin { group: PortGroup, number: u8, } impl PortPin { pub const PB02: Self = Self { group: PortGroup::B, number: 2, }; // 等等... }
/// PORT 外设的接口。 pub struct PORT(()); impl PORT { /// 创建一个新的 PORT。 /// /// # Safety /// /// 仅当不存在 PORT 的其他实例时才应调用此方法。 pub unsafe fn steal() -> Self { Self(()) }
/// SAFETY: 返回的指针指向 MMIO,因此该指针(以及任何派生指针) /// 永远不能转换为引用,且只允许对其进行易失性读写。 const fn ptr(&mut self) -> mut PORTRegisterBlock { 0x41000000 as mut PORTRegisterBlock }
/// 返回 PORT 控制寄存器中索引为 N 的组。
pub fn group(&mut self, group: PortGroup) -> PORTGroup<'_> {
PORTGroup {
group: unsafe { &raw mut (*self.ptr()).groups[group as usize] },
_port: self,
}
}
pub fn set_pin_direction(
&mut self,
pin: PortPin,
direction: PortDirection,
) {
self.group(pin.group)
.set_pins_direction(1u32 << pin.number as u32, direction);
}
pub fn set_pin_output(&mut self, pin: PortPin, level: bool) {
self.group(pin.group)
.set_pins_output(1u32 << pin.number as u32, level);
}
}
pub struct PORTGroup<'a> {
group: *mut PORTGroupRegisterBlock,
_port: &'a mut PORT,
}
impl PORTGroup<'_> {
pub fn write_dir(&mut self, value: u32) {
unsafe {
let dir = &raw mut (*self.group).dir;
dir.write_volatile(value);
};
}
pub fn read_dir(&mut self) -> u32 {
unsafe {
let dir = &raw mut (*self.group).dir;
dir.read_volatile()
}
}
pub fn write_out(&mut self, value: u32) {
unsafe {
let out = &raw mut (*self.group).out;
out.write_volatile(value);
}
}
pub fn read_out(&mut self) -> u32 {
unsafe {
let out = &raw mut (*self.group).out;
out.read_volatile()
}
}
pub fn set_pins_direction(&mut self, mask: u32, direction: PortDirection) {
let mut value = self.read_dir();
match direction {
PortDirection::Input => value &= !mask,
PortDirection::Output => value |= mask,
}
self.write_dir(value);
}
pub fn set_pins_output(&mut self, mask: u32, level: bool) {
let mut value = self.read_out();
match level {
false => value &= !mask,
true => value |= mask,
}
self.write_out(value);
}
}
我们还可以暴露 PORT 外设的更多功能,但上面的代码对我们来说已经足够了。
注意,我们把 PORT 标记为 pub,但没有标记 PORTRegisterBlock 和 PORT::ptr() 方法。这意味着只有 PORT 及其公开方法在模块外部可见,因此应用代码的其余部分无法意外绕过我们构建的安全抽象9。
值得指出的是,像这里这样让寄存器不可访问,对于公开共享的库来说可能并不是最佳实践,因为这会让下游用户很难绕过所提供抽象的任何限制。
最后,我们的应用函数变得非常简单:
const LED0: PortPin = PortPin::PB02;
/// 设置 LED0 开启或关闭。
fn set_led0(port: &mut PORT, on: bool) {
port.set_pin_direction(LED0, PortDirection::Output);
// 当引脚输出为低电平时,LED0 点亮。
port.set_pin_output(LED0, !on);
}
现在我们的主应用代码中已经没有任何不安全代码了!我是说,除了 unsafe { PORT::steal() }。我们可以通过添加运行时检查为 steal() 做一个安全封装,但由于 ARMv6-M 没有原子比较并交换指令,要安全地做到这一点需要建立一个临界区(我们稍后会看到)。
一个 HAL crate
为了更好地将硬件抽象代码与应用代码分离,我们可以把硬件抽象代码移到另一个 crate 中(crate 基本上就是一个 Rust 库10)。
严格来说,Rust crate 是 Rust 语言的编译单元。它可以是库 crate 或二进制 crate。Cargo.toml 清单定义一个 Rust 包,该包最多包含一个库 crate,以及任意数量的二进制 crate。Cargo 依赖是另一个包,其中包含一个库 crate,你的代码链接到它。
我们可以先编辑根 Cargo.toml 来定义一个工作区:
[workspace]
[package]
name = "embedded-rust-from-scratch"
version = "0.1.0"
edition = "2024"
[dependencies]
然后我们可以创建新的 crate,并将其添加为根 crate 的依赖项:
$ cargo new pic32cm6408pl10-hal --lib
Creating library `pic32cm6408pl10-hal` package
Adding `pic32cm6408pl10-hal` as member of workspace at `/home/rodrigodd/Projects/embedded-rust-from-scratch`
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
$ cargo add --path ./pic32cm6408pl10-hal
Adding pic32cm6408pl10-hal (local) to dependencies
我们的 Cargo.toml 随后变成:
[workspace]
members = ["pic32cm6408pl10-hal"]
[package]
name = "embedded-rust-from-scratch"
version = "0.1.0"
edition = "2024"
[dependencies]
pic32cm6408pl10-hal = { version = "0.1.0", path = "pic32cm6408pl10-hal" }
这里的 hal 代表硬件抽象层(HAL),这是嵌入式软件中的常用术语。
然后我们可以把 port.rs 移动到 pic32cm6408pl10-hal/src/,并把 src/main.rs 中的 global_asm! 和 mod port 代码移动到 pic32cm6408pl10-hal/src/lib.rs。我们还需要给 mod port 加上 pub,并在 lib.rs 顶部加上 #![no_std]。
#![no_std]
#![no_main]
use core::panic::PanicInfo;
use pic32cm6408pl10_hal::port::{PORT, PortDirection, PortPin};
#[panic_handler]
fn panic_handler(_: &PanicInfo) -> ! {
loop {}
}
const LED0: PortPin = PortPin::PB02;
/// Set LED0 On or Off.
fn set_led0(port: &mut PORT, on: bool) {
port.set_pin_direction(LED0, PortDirection::Output);
// LED0 turns on when the pin output is low.
port.set_pin_output(LED0, !on);
}
#[unsafe(no_mangle)]
extern "C" fn main() {
// SAFETY: PORT::steal() is only called here.
let mut port = unsafe { PORT::steal() };
let mut toggle: bool = false;
loop {
toggle = !toggle;
set_led0(&mut port, toggle);
delay_1s();
}
}
pub fn delay_1s() {
let count: u32 = 1_333_333;
// for instruction cycle counts, see:
// Cortex-M0+ Technical Reference Manual, Table 3-1
unsafe {
core::arch::asm!(
"2:",
"subs {count}, #1", // 1 cycle
"bne 2b", // 2 cycles if taken, 1 otherwise
count = inout(reg) count => _,
options(nomem, nostack),
);
}
}
#![no_std]
pub mod port;
core::arch::global_asm! {
r#"
/* Declare `_start` label as an externally visible symbol */
.global _start
/* specifies that the symbol `_start` points to a thumb instruction */
.thumb_func
/* our _start routine */
_start:
/* zero .bss section */
.Lzero_bss:
/* load a value 0 and pointers to the start and end of bss in registers */
movs r0, #0
ldr r1, =bss_start
ldr r2, =bss_end
.Lzero_bss_loop:
/* if r1 is at bss_end, stop the loop and proceed to copy .data */
cmp r1, r2
bcs .Lcopy_data
/* store a 32bit 0 at r1 address */
str r0, [r1]
/* increment r1 by 4, then loop */
adds r1, #4
b .Lzero_bss_loop
/* copy .data from load address to RAM */
.Lcopy_data:
/* load pointers to the start and end of .data in FLASH and RAM */
ldr r0, =load_data_start
ldr r1, =data_start
ldr r2, =data_end
.Lcopy_data_loop:
/* if r1 is at data_end, stop the loop and proceed to call main */
cmp r1, r2
bcs .Lcall_main
/* load a 32bit value from r0 address, and store it at r1 address */
ldr r3, [r0]
str r3, [r1]
/* increment r0 and r1 by 4, then loop */
adds r0, #4
adds r1, #4
b .Lcopy_data_loop
/* call the main function. */
.Lcall_main:
/* main has no arguments, so no setup required */
bl main
/* if main returns, just run an infinite loop */
.Lhang:
b .Lhang
"#
}
今后我们添加的任何硬件抽象都放入 pic32cm6408pl10-hal crate,这样就能跨项目共享这个 crate。我们还可以把 linker.ld 链接脚本也移到 HAL crate 中,使其更具可共享性,但这需要一些额外的设置(参见 cortex-m-rt crate 作为参考)。
定时器与中断
文章标题:Embedded Rust from Scratch
正文: 好了,我们现在有了相对安全的微控制器应用代码。接下来,让我们改进 delay_1s 函数。目前它只是在一个忙循环中递减计数器。更高效的做法是使用定时器外设。使用定时器可以避免在延时期间让 CPU 一直忙碌,这样我们就能在定时器运行的同时并发地做其他工作,或者干脆让 CPU 停机以节省一些功耗。
在这个微控制器上,我们有几个定时器外设可供选择:
- ARMv6-M 内核外设 SysTick,
- 3 个 TC(Timer/Counter,定时器/计数器)外设,
- 1 个 TCC(Timer/Counter for Control Applications,用于控制应用的定时器/计数器)外设,以及
- 1 个 RTC(Real Time Counter,实时计数器)外设。
每个定时器都有不同的计数器寄存器位宽(从 8 位到 32 位,外加预分频器)和功能集(波形生成、输入捕获、日历模式、更多中断事件等)。由于我们只是用定时器实现简单的延时,SysTick 定时器就足够了,而且它也是许多 Cortex-M 微控制器都具备的定时器,所以学习它的可迁移性更强。
ARMv6-M 的 SysTick 定时器是一个简单的 24 位计数器。它基本上有 3 个寄存器:
- 状态与控制寄存器(SYST_CSR):用于使能定时器及其异常、更改时钟源,以及读取“已计数到 0”标志。
- 重装载值寄存器(SYST_RVR):每当定时器计数到 0 时,就会回绕到这个值。
- 当前值寄存器(SYST_CVR):读取时返回当前计数值,写入时将计数器复位为 0。
它还有一个校准寄存器,可选地包含用于 10 ms 定时的参考重装载值,以及诸如是否实现了外部参考时钟之类的信息。但这些在 PIC32CM PL10 上不可用。
基于此,我们已经可以为 SysTick 创建一个抽象:
/// Interface for the SysTick Peripheral.
pub struct SysTick(());
impl SysTick {
/// Create a new `SysTick`.
///
/// # Safety
///
/// This method should only be called if no other instance of `SysTick`
/// exists.
pub unsafe fn steal() -> Self {
Self(())
}
/// SAFETY: The return pointer points to MMIO, therefore the pointer (and
/// any derivative) can never be cast to a reference, and only volatile
/// reads and writes are allowed on it.
fn ptr(&mut self) -> *mut SysTickRegisterBlock {
0xE000E010 as *mut SysTickRegisterBlock
}
/// Initialize the timer to count to 0 every `period` clock cycles, and
/// optionally enable the SysTick exception.
pub fn init(&mut self, period: u32, tick_interrupt: bool) {
self.write_control(false, false);
// The counter goes from RELOAD to 0, so a period is RELOAD + 1 cycles.
self.write_reload_value(period - 1);
self.reset_counter();
self.read_control();
self.write_control(true, tick_interrupt);
}
/// Read Control and Status Register
///
/// This function reads `SYST_CSR`. Reading this register clears
/// `COUNTFLAG`.
pub fn read_control(&mut self) -> u32 {
unsafe {
let reg = &raw mut (*self.ptr()).syst_csr;
reg.read_volatile()
}
}
/// Return true if the counter has counted to 0 at some point since the last
/// read of `SYST_CSR`
///
/// This function reads `SYST_CSR`.
pub fn has_counted_to_zero(&mut self) -> bool {
(self.read_control() & (1 << 16)) != 0
}
/// Write the Control and Status Register.
///
/// If `enable` is true, enables the timer counting. If `tick_interrupt` is
/// true, triggers the SysTick exception on every count to 0.
pub fn write_control(&mut self, enable: bool, tick_interrupt: bool) {
unsafe {
let reg = &raw mut (*self.ptr()).syst_csr;
reg.write_volatile(
(1 << 2) | (tick_interrupt as u32) << 1 | (enable as u32),
)
}
}
/// 写入重装载值寄存器。
///
/// `value` 应当适合 24 位。
pub fn write_reload_value(&mut self, value: u32) {
unsafe {
let reg = &raw mut (*self.ptr()).syst_rvr;
reg.write_volatile(value);
}
}
/// 返回当前计数值。
pub fn current_count(&mut self) -> u32 {
unsafe {
let reg = &raw mut (*self.ptr()).syst_cvr;
reg.read_volatile()
}
}
/// 将计数器重置为 0。
pub fn reset_counter(&mut self) {
unsafe {
let reg = &raw mut (*self.ptr()).syst_cvr;
reg.write_volatile(0x0);
}
}
}
// 参见 "ARMv6-M Architecture Reference Manual" 中的表 B3-13
#[repr(C)]
struct SysTickRegisterBlock {
/// 控制与状态寄存器 (SYST_CSR)
///
/// | 位 | 名称 | 功能 |
/// | --- | --- | --- |
/// | 16 | COUNTFLAG | 计数到 0 时置 1。读取时清除。 |
/// | 2 | CLKSOURCE | 始终为 1。 |
/// | 1 | TICKINT | 1 启用 SysTick 异常。 |
/// | 0 | ENABLE | 1 启用计数器 |
syst_csr: u32,
/// 重装载值寄存器 (SYST_RVR)
///
/// | 位 | 名称 | 功能 |
/// | --- | --- | --- |
/// | 31:24 | 保留 |
/// | 23:0 | RELOAD | 到达 0 后加载到 SYST_CVR 的值。
syst_rvr: u32,
/// 当前值寄存器 (SYST_CVR)
///
/// | 位 | 名称 | 功能 |
/// | --- | --- | --- |
/// | 31:24 | 保留 |
/// | 23:0 | CURRENT | 当前计数值 |
syst_cvr: u32,
/// 校准值寄存器 (SYST_CALIB)
///
/// | 位 | 名称 | 功能 |
/// | --- | --- | --- |
/// | 31 | NOREF | 始终为 1 - 未实现参考时钟 |
/// | 30 | SKEW | 始终为 1 - 校准值不精确 |
/// | 29:24 | 保留 |
/// | 23:0 | TENMS | 始终为 0 - 未提供校准值 |
_syst_calib: u32,
}
我们还可以在 HAL crate 的所有外设之上创建一个 Peripherals 包装类型,这样应用代码只需进行一次 unsafe 调用,而不是每个外设调用一次:
/// 所有外设的接口。
pub struct Peripherals {
pub port: PORT,
pub sys_tick: SysTick,
}
impl Peripherals {
/// 创建一个新的 `Peripherals`。
///
/// # 安全性
///
/// 此方法只应被调用一次。
pub unsafe fn steal() -> Self {
Self {
port: unsafe { PORT::steal() },
sys_tick: unsafe { SysTick::steal() },
}
}
}
然后我们可以将主代码重写为:
const LED0: PortPin = PortPin::PB02;
/// 打开或关闭 LED0。
fn set_led0(port: &mut PORT, on: bool) {
port.set_pin_direction(LED0, PortDirection::Output);
// 引脚输出为低电平时 LED0 点亮。
port.set_pin_output(LED0, !on);
}
#[unsafe(no_mangle)]
extern "C" fn main() {
// 安全性:Peripherals::steal() 仅在此处调用。
let mut peripherals = unsafe { Peripherals::steal() };
let mut toggle: bool = false;
loop {
toggle = !toggle;
set_led0(&mut peripherals.port, toggle);
delay_1s(&mut peripherals.sys_tick);
}
}
pub fn delay_1s(sys_tick: &mut SysTick) {
// 主时钟为 4MHz
sys_tick.init(4_000_000, false);
while !sys_tick.has_counted_to_zero() {}
// 停止定时器
sys_tick.write_control(false, false);
}
不错!我们仍然在 while !sys_tick.has_counted_to_zero() {} 中忙等待循环,但我们现在可以在该循环内运行其他代码,而不干扰我们的计时。或者,我们可以执行 Wait for Interrupt (WFI) 或 Wait for Event (WFE) 指令,让微控制器进入低功耗模式,直到定时器触发中断。
要让这生效,我们需要实现 SysTick 异常处理程序,否则中断发生时我们的代码会崩溃。让我们也借此机会完整地填写整个向量表。
文章标题:从零开始的嵌入式 Rust
正文: 之前我们只在链接脚本中实现了初始栈指针和 Reset 异常处理程序。我们可以改为在 Rust 中创建一个包含所有异常处理程序的数组,把它放到一个特殊的段中,然后用链接器把它放到正确的位置。
// We declare an extern symbol for each exception handler
unsafe extern "C" {
// See Table B1-3 of "ARMv6-M Architecture Reference Manual"
fn Reset();
fn NMI();
fn HardFault();
fn SVCall();
fn PendSV();
fn SysTick();
// See Table 4-3 of PIC32CM6408PL10048 Data Sheet
fn SYSTEM();
fn WDT();
fn RTC();
fn EIC();
fn NVMCTRL();
fn DMAC();
fn EVSYS();
fn SERCOM0();
fn SERCOM1();
fn TC0();
fn TC1();
fn TC2();
fn TCC0();
fn ADC0();
fn AC();
}
// A `fn()` is non-nullable, create a union that allows NULL.
#[repr(C)]
pub union Vector {
handle: unsafe extern "C" fn(),
reserved: u32,
}
#[used]
#[unsafe(link_section = ".vector_table.handlers")]
pub static VECTOR_TABLE: [Vector; 47] = [
// See Table B1-3 of "ARMv6-M Architecture Reference Manual"
Vector { handle: Reset },
Vector { handle: NMI },
Vector { handle: HardFault },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { handle: SVCall },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { handle: PendSV },
Vector { handle: SysTick },
// See Table 4-3 of PIC32CM6408PL10048 Data Sheet
Vector { handle: SYSTEM },
Vector { handle: WDT },
Vector { handle: RTC },
Vector { handle: EIC },
Vector { handle: NVMCTRL },
Vector { handle: DMAC },
Vector { handle: EVSYS },
Vector { handle: SERCOM0 },
Vector { handle: SERCOM1 },
Vector { handle: TC0 },
Vector { handle: TC1 },
Vector { handle: TC2 },
Vector { handle: TCC0 },
Vector { handle: ADC0 },
Vector { handle: AC },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
Vector { reserved: 0 },
];
我还在 lib.rs 的 global_asm! 块中把符号 _start 重命名为 Reset,以与异常名称相匹配。然后在链接脚本中:
SECTIONS {
/* define the .vector_table at start of FLASH */
.vector_table ORIGIN(FLASH) : {
/* initial Stack Pointer.
* Start at the end of SRAM (SP decreases as stack grows) */
LONG(ORIGIN(SRAM) + LENGTH(SRAM))
/* Exception handlers */
KEEP(*(.vector_table.handlers))
}
/* ... */
}
/* Mark `Reset` as the entry so the linker does not warn about
* a missing `_start` */
ENTRY(Reset)
我们使用 KEEP 语句,是因为 rustc 默认会向链接器传递 --gc-sections,这会让链接器丢弃任何内部没有符号被引用的段。请注意,在 Rust 代码中我们只在 extern 块里声明了每个符号,但并没有真正实现它们。这样我们就能从应用程序中实现这些中断处理程序。
另一点需要注意的是,我们使用 extern "C" 作为这些函数的 ABI。这是因为在 ARMv6-M 架构中,C ABI 与处理器自身调用中断处理程序所使用的 ABI 是相同的。它们并不总是对齐的,在这种情况下,我们就必须用汇编编写一个跳板函数来使其工作。11
有些 ARM 异常处理程序会通过寄存器或栈传递一些额外信息。它们仍然与调用约定兼容,但需要一段 trampoline 才能访问那些信息。
按照目前的写法,应用程序代码需要实现所有中断处理程序,否则链接时会出现“undefined symbol”错误。为了避免这种情况,我们可以调整链接器脚本,提供一个回退实现。首先,我们在 HAL crate 中定义这个默认处理程序:
#[unsafe(export_name = "DefaultExceptionHandler")]
unsafe extern "C" fn default_exception_handler() {}
然后在链接器脚本中,我们可以使用 PROVIDE 语句,让这个异常处理程序成为任何未定义异常处理程序的回退符号。当应用程序代码实际提供了中断实现时,PROVIDE 语句不会生效:
PROVIDE(NMI = DefaultExceptionHandler);
PROVIDE(HardFault = DefaultExceptionHandler);
PROVIDE(SVCall = DefaultExceptionHandler);
PROVIDE(PendSV = DefaultExceptionHandler);
PROVIDE(SysTick = DefaultExceptionHandler);
PROVIDE(SYSTEM = DefaultExceptionHandler);
PROVIDE(WDT = DefaultExceptionHandler);
PROVIDE(RTC = DefaultExceptionHandler);
PROVIDE(EIC = DefaultExceptionHandler);
PROVIDE(NVMCTRL = DefaultExceptionHandler);
PROVIDE(DMAC = DefaultExceptionHandler);
PROVIDE(EVSYS = DefaultExceptionHandler);
PROVIDE(SERCOM0 = DefaultExceptionHandler);
PROVIDE(SERCOM1 = DefaultExceptionHandler);
PROVIDE(TC0 = DefaultExceptionHandler);
PROVIDE(TC1 = DefaultExceptionHandler);
PROVIDE(TC2 = DefaultExceptionHandler);
PROVIDE(TCC0 = DefaultExceptionHandler);
PROVIDE(ADC0 = DefaultExceptionHandler);
PROVIDE(AC = DefaultExceptionHandler);
对我们的应用来说,默认中断处理程序就足够了,因为我们只是想等待中断发生,而且该外设已经有一个标志位来表示定时器已计数到零。现在我们的应用程序代码变成:
pub fn delay_1s(sys_tick: &mut SysTick) {
// Main clock is at 4MHz
sys_tick.init(4_000_000, true);
while !sys_tick.has_counted_to_zero() {
wait_for_interrupt();
}
// Stop the timer
sys_tick.write_control(false, false);
}
fn wait_for_interrupt() {
unsafe { core::arch::asm!("WFI") }
}
这样一来,微控制器现在应该会消耗更少的电量12!
根据数据手册,考虑到我使用的是内部时钟源,它应该会从约 5 mA 的电流降到约 1 mA。但数据手册只提供了 24 MHz 下的数值,而我们运行在默认的 4 MHz,所以实际值很可能远低于这个数。我本想自己测量,但这需要对开发板做一些硬件改造。
读取按钮
好,接下来我们要做的是用中断等待按钮按下。我的板子上有一个名为 SW0 的按钮,连接到引脚 PB03。当按钮断开(未按下)时,引脚浮空;当按钮闭合(按下)时,引脚通过一个 1 kΩ 串联电阻连接到 GND。为了让它断开时不浮空,我们需要启用微控制器引脚的内部上拉电阻。
我们先从使用 PORT 外设读取按钮开始,然后再设置中断。要读取一个引脚,我们不仅需要将 DIR 配置为输入,还要在 PINCFG 中启用输入缓冲,然后从 IN 读取值。我们还需要在 PINCFG 中启用上拉,而这只有在 OUT 设置为 1 时才有效。
为此,我们需要在 PORT 类型中添加一些额外的方法:
pub struct PortPinConfig {
/// Enable peripheral multiplexer.
pub peripheral_multiplexer: bool,
/// Enable connection between the pin and the peripherals, including PORT
/// itself.
pub input_buffer_enable: bool,
/// Enable pull-up resistor. Pulls with ~20kΩ. Requires `OUT=1` to work.
pub pull_enable: bool,
/// Enable output driver slew rate limit.
pub slew_rate_limit: bool,
}
#[derive(Clone, Copy)] pub struct PortPin { group: PortGroup, number: u8, } impl PortPin { pub const PB02: Self = groupb(2); pub const PB03: Self = groupb(3); // 等等…… }
const fn groupb(number: u8) -> PortPin { PortPin { group: PortGroup::B, number, } }
impl PORT { pub fn set_pin_config(&mut self, pin: PortPin, config: PortPinConfig) { self.group(pin.group).set_pin_config(pin.number, config); }
pub fn read_pin(&mut self, pin: PortPin) -> bool { self.group(pin.group).read_pin(pin.number) } // …… }
impl PORTGroup<'_> { fn set_pin_config(&mut self, number: u8, config: PortPinConfig) { unsafe { let reg = &raw mut (*self.group).pincfg[number as usize]; let value = (config.slew_rate_limit as u8) << 4 | (config.pull_enable as u8) << 2 | (config.input_buffer_enable as u8) << 1 | (config.peripheral_multiplexer as u8); reg.write_volatile(value); } }
fn read_pin(&self, number: u8) -> bool { unsafe { let reg = &raw const (*self.group).r#in; reg.read_volatile() & (1 << number) != 0 } } // …… }
然后我们可以修改 `main`,例如:当按钮被按下时让 LED 闪得更快。
// 低电平表示按下 const SW0: PortPin = PortPin::PB03;
#[unsafe(no_mangle)] extern "C" fn main() { // SAFETY:Peripherals::steal() 仅在此处调用。 let mut peripherals = unsafe { Peripherals::steal() };
let port = &mut peripherals.port; let sys_tick = &mut peripherals.sys_tick;
// 配置 SW0 port.set_pin_direction(SW0, PortDirection::Input); port.set_pin_config( SW0, PortPinConfig { peripheral_multiplexer: false, input_buffer_enable: true, pull_enable: true, slew_rate_limit: false, }, ); port.set_pin_output(SW0, true);
let mut toggle: bool = false; loop { toggle = !toggle; set_led0(port, toggle); if !port.read_pin(SW0) { delay(sys_tick, 100); } else { delay(sys_tick, 1000); } } }
pub fn delay(sys_tick: &mut SysTick, ms: u32) { // 主时钟为 4MHz sys_tick.init(ms * 4_000, true); while !sys_tick.has_counted_to_zero() { wait_for_interrupt(); } // 停止定时器 sys_tick.write_control(false, false); }
我们本可以做一个更高层的引脚配置抽象,避免让应用代码去维护那 3 个寄存器的同步,但目前这样就足够了。
如果现在测试我们的应用,可以看到按下按钮时 LED 会快速闪烁!
但要注意一个问题:我们每次切换时只读取一次按钮输入,而且是在切换 LED 之后紧接着读取,所以如果我们在 LED 切换后立刻按下按钮,可能需要等最多 1 秒应用才能检测到按下。为了避免这种情况,我们需要配置引脚中断。
## 处理引脚中断
要让中断工作,我们需要让另外几个外设运转起来:
- 嵌套向量中断控制器(NVIC):这是 ARM 内核的外设,用于使能中断并设置其优先级。
- 外部中断控制器(EIC):用于配置 EXTINT 线的中断,例如使能边沿或电平检测,以及滤波。
- 主时钟(MCLK):用于为每个外设单独使能时钟信号。我们需要使能 EIC 的时钟。
- PORT:我们需要增加对引脚复用的支持,这样就可以把我们的 PB03 引脚连接到 EXTINT[3] 线。
以下是每个外设的代码:
pub struct MCLK(()); impl MCLK { /// 创建一个新的 MCLK。 /// /// # Safety /// /// 仅当不存在其他 MCLK 实例时,才应调用此方法。 pub unsafe fn steal() -> Self { Self(()) }
/// SAFETY: The return pointer points to MMIO, therefore the pointer (and /// any derivative) can never be cast to a reference, and only volatile /// reads and writes are allowed on it. fn ptr(&mut self) -> mut MCLKRegisterBlock { 0x40000800 as mut MCLKRegisterBlock }
pub fn enable_peripheral_clock( &mut self, peripheral: MclkPeripheral, enable: bool, ) { unsafe { let p = peripheral as u8; let idx = p / 32; let bit = p % 32; let reg = &raw mut (*self.ptr()).ahbmask; let reg = reg.add(idx as usize); let value = reg.read_volatile(); let value = match enable { true => value | (1 << bit), false => value & !(1 << bit), }; reg.write_volatile(value); } } }
#[repr(C)] struct MCLKRegisterBlock { intenclr: u8, intenset: u8, intflag: u8, cpudiv: u8, _reserved: [u8; 12], ahbmask: u32, apbamask: u32, apbbmask: u32, apbcmask: u32, }
#[repr(u8)] pub enum MclkPeripheral { ApbaAhb, ApbbAhb, ApbcAhb, DsuAhb, HmatrixhsAhb, NvmctrlAhb, HsramAhb, Dmac1Ahb, Pac1Ahb = 8, BromAhb, Pac2Ahb = 32, PmApb, MclkApb, RstcApb, OscctrlApb, Osc32kctrlApb, SupcApb, GclkApb, WdtApb = 40, RtcApb = 41, EicApb = 42, PortApb = 64, DsuApb, NvmctrlApb, Dmac2Apb, MtbApb, HmatrixhsApb, EvsysApb = 96, Sercom0Apb, Sercom1Apb, Tc0Apb, Tc1Apb, Tc2Apb, Tcc0Apb, Adc0Apb, AcApb = 104, CclApb, PtcApb, SysctrlApb, }
pub struct NVIC(()); impl NVIC { /// Create a new NVIC. /// /// # Safety /// /// This method should only be called if no other instance of NVIC /// exists. pub unsafe fn steal() -> Self { Self(()) }
/// SAFETY: The return pointer points to MMIO, therefore the pointer (and /// any derivative) can never be cast to a reference, and only volatile /// reads and writes are allowed on it. fn ptr(&mut self) -> mut NVICRegisterBlock { 0xE000E100 as mut NVICRegisterBlock }
pub fn enable_interrupt(&mut self, interrupt: NvicInterrupt, enable: bool) { if enable { unsafe { let reg = &raw mut (self.ptr()).nvic_iser; reg.write_volatile(1u32 << interrupt as u8); } } else { unsafe { let reg = &raw mut (self.ptr()).nvic_icer; reg.write_volatile(1u32 << interrupt as u8); } } }
/// Clear pending interrupt pub fn clear_interrupt(&mut self, interrupt: NvicInterrupt) { unsafe { let reg = &raw mut (*self.ptr()).nvic_icpr; reg.write_volatile(1u32 << interrupt as u8); } } }
#[repr(C)] // See Table B3-18 in "ARMv6-M Architecture Reference Manual" struct NVICRegisterBlock { nvic_iser: u32, _reserved: [u8; 0x7c], nvic_icer: u32, _reserved2: [u8; 0x7c], nvic_ispr: u32, _reserved3: [u8; 0x7c], nvic_icpr: u32, _reserved4: [u8; 0x17c], nvic_ipr: [u32; 8], _reserved5: [u8; 124], }
// See Table 4-3 of PIC32CM6408PL10048 Data Sheet #[repr(u8)] pub enum NvicInterrupt { System, Wdt, Rtc, Eic, Nvmctrl, Dmac, Evsys, Sercom0, Sercom1, Tc0, Tc1, Tc2, Tcc0, Adc0, Ac, }
pub struct EIC(()); impl EIC { /// Create a new EIC. /// /// # Safety /// /// This method should only be called if no other instance of EIC /// exists. pub unsafe fn steal() -> Self { Self(())
/// SAFETY: The return pointer points to MMIO, therefore the pointer (and /// any derivative) can never be cast to a reference, and only volatile /// reads and writes are allowed on it. fn ptr(&mut self) -> mut EICRegisterBlock { 0x40002800 as mut EICRegisterBlock }
pub fn enable(&mut self, enable: bool) { unsafe { let ctrla = &raw mut (self.ptr()).ctrla; let syncbusy = &raw mut (self.ptr()).syncbusy;
// 启用或禁用 EIC ctrla.write_volatile((enable as u8) << 1); // 等待 SYNCBUSY.ENABLE,这样受启用保护的寄存器(如 // CONFIG)只会在 EIC 真正禁用之后才被写入。 while (syncbusy.read_volatile() & (1u32 << 1)) != 0 {} } }
pub fn set_extint_config( &mut self, extint: u8, filter: bool, sense: EicSensing, ) { unsafe { let config0 = &raw mut (*self.ptr()).config0;
// 配置引脚感测。 let idx = extint as usize / 8; let offset = (extint % 8) * 4; let reg = config0.add(idx); let value = reg.read_volatile(); let v = ((filter as u32) << 3) | (sense as u32);
reg.write_volatile((value & !(0x0F << offset)) | (v << offset)); } }
pub fn get_extint_config(&mut self, extint: u8) -> (bool, EicSensing) { unsafe { let config0 = &raw mut (*self.ptr()).config0;
// 读取引脚感测配置。 let idx = extint as usize / 8; let offset = (extint % 8) * 4; let reg = config0.add(idx); let value = reg.read_volatile() >> offset; ( value & (1 << 3) != 0, EicSensing::try_from((value & 0b111) as u8) .unwrap_or(EicSensing::None), ) } }
/// 启用或禁用 EXTINTn 的中断,其中 n 为 extint。 pub fn enable_interrupt(&mut self, extint: u8, enable: bool) { unsafe { if enable { let reg = &raw mut (self.ptr()).intenset; reg.write_volatile(1u32 << extint); } else { let reg = &raw mut (self.ptr()).intenclr; reg.write_volatile(1u32 << extint); } } }
/// 清除 EXTINTn 的中断标志,其中 n 为 extint。 pub fn clear_interrupt(&mut self, extint: u8) { unsafe { let reg = &raw mut (*self.ptr()).intflag; reg.write_volatile(1u32 << extint); } } }
#[repr(C)] struct EICRegisterBlock { ctrla: u8, nmictr: u8, nmiflag: u16, syncbusy: u32, evctrl: u32, intenclr: u32, intenset: u32, intflag: u32, asynch: u32, config0: u32, config1: u32, }
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum EicSensing { None = 0, Rise = 1, Fall = 2, Both = 3, High = 4, Low = 5, // Reserved = 6-7, } impl TryFrom<u8> for EicSensing { type Error = (); fn try_from(value: u8) -> Result<Self, Self::Error> { Ok(match value { 0 => Self::None, 1 => Self::Rise, 2 => Self::Fall, 3 => Self::Both, 4 => Self::High, 5 => Self::Low, _ => return Err(()), }) } }
以及我们用于配置引脚复用的新 PORT API:
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct PortPin { group: PortGroup, number: u8, } impl PortPin { pub const PB02: Self = groupb(2); pub const PB03: Self = groupb(3); // 等等……
/// 返回关联的 EXTINTn 线编号(如果有的话)。 /// /// 参见数据手册第 2.3 节 "Pinout and Multiplexing"。 pub fn extint(&self) -> Option<u8> { Some(match *self { Self::PB02 => 2, Self::PB03 => 3, // 等等…… _ => return None, }) } }
// ……
impl PORT { pub fn set_pin_mux(&mut self, pin: PortPin, peripheral_function: u8) { self.group(pin.group) .set_pin_mux(pin.number, peripheral_function); } // …… }
impl PORTGroup<'_> { fn set_pin_mux(&self, number: u8, peripheral_function: u8) { unsafe { let idx = number / 2; let offset = 4 (number % 2); let reg = &raw mut (self.group).pmux[idx as usize]; let value = reg.read_volatile(); reg.write_volatile( (value & !(0xF << offset)) | (peripheral_function << offset), ); } } // …… }
我们还给 Peripherals 结构体添加了 mclk、eic 和 nvic 字段。
然后在应用代码中,我们为引脚启用外设复用器,将其外设功能设置为 EXTINT[3],启用 EIC 的时钟,将 EIC 配置为在 EXTINT[3] 低电平时触发中断,最后在 NVIC 中启用 EIC 中断:
fn config_sw0_interrupt( port: &mut PORT, mclk: &mut MCLK, eic: &mut EIC, nvic: &mut NVIC, ) { // 将 SW0 配置为上拉输入,连接到 EXTINT[3]。 port.set_pin_direction(SW0, PortDirection::Input); port.set_pin_mux(SW0, 0); port.set_pin_config( SW0, PortPinConfig { peripheral_multiplexer: true, input_buffer_enable: true, pull_enable: true, slew_rate_limit: false, }, ); port.set_pin_output(SW0, true);
// 启用 EIC 时钟 mclk.enable_peripheral_clock(MclkPeripheral::EicApb, true);
let extint = SW0.extint().unwrap(); eic.set_extint_config(extint, false, EicSensing::Low); eic.enable_interrupt(extint, true); eic.enable(true);
nvic.enable_interrupt(NvicInterrupt::Eic, true); }
我们使用电平检测,因为边沿检测需要 EIC 由通用时钟(GCLK)驱动,那又会是另一个需要配置的外设。
这样一来,如果你按下按钮,EIC 中断标志应该会被激活,使微控制器跳转到中断处理程序!
但如果我们在中断中什么都不做、直接返回,中断标志会继续保持激活状态,因此即使我们松开按钮,中断也会再次触发,实际上会让微控制器卡死。
所以我们需要用一个能清除 EIC 外设挂起标志的处理程序覆盖默认的中断处理程序。我们还需要把中断从低电平触发改为高电平触发。这样它就只会在按钮松开时再次中断。
我们还可以设置一个全局变量来跟踪按钮状态,这样在每次 wait_for_interrupt 之后就能从 main 中读取它。为此我们使用 AtomicBool,因为 main 和中断处理程序之间共享的全局变量,只有在具有某种同步机制的情况下,才能通过共享引用安全地修改(static mut 每次访问都需要 unsafe)。ARMv6-M 没有原子的读-改-写指令,但这里我们只需要原子加载和存储,而且 Ordering::Relaxed 就足够了,因为我们不使用该标志来同步对任何其他数据的访问。
最终代码如下:
use core::{ panic::PanicInfo, sync::atomic::{AtomicBool, Ordering}, }; // ……
static BUTTON_DOWN: AtomicBool = AtomicBool::new(false);
#[unsafe(export_name = "EIC")] extern "C" fn eic_interrupt_handler() { let extint = SW0.extint().unwrap();
// 在此处调用 EIC::steal() 是不健全的! let mut eic = unsafe { EIC::steal() };
eic.enable(false); let (_, sense) = eic.get_extint_config(extint); if sense == EicSensing::High { eic.set_extint_config(extint, false, EicSensing::Low); BUTTON_DOWN.store(false, Ordering::Relaxed); } else { eic.set_extint_config(extint, false, EicSensing::High); BUTTON_DOWN.store(true, Ordering::Relaxed); } eic.clear_interrupt(extint); eic.enable(true); }
#[unsafe(no_mangle)] extern "C" fn main() { // SAFETY: Peripherals::steal() is only called here. let mut peripherals = unsafe { Peripherals::steal() };
let sys_tick = &mut peripherals.sys_tick; let port = &mut peripherals.port; let mclk = &mut peripherals.mclk; let eic = &mut peripherals.eic; let nvic = &mut peripherals.nvic;
config_sw0_interrupt(port, mclk, eic, nvic);
let mut toggle: bool = false; loop { toggle = !toggle; set_led0(port, toggle); let flag = BUTTON_DOWN.load(Ordering::Relaxed); let ms = if flag { 100 } else { 1000 };
// Main clock is at 4MHz sys_tick.init(ms * 4_000, true); let mut new_flag = flag; while !sys_tick.has_counted_to_zero() && flag == new_flag { wait_for_interrupt(); new_flag = BUTTON_DOWN.load(Ordering::Relaxed); }
// Stop the timer sys_tick.write_control(false, false); } }
现在,LED 恰好在按钮被按下时开始快速闪烁!
## 临界区
但有一个问题:我们需要在中断处理程序中访问 `&mut EIC`,但它只在 `main` 中可用。我只是在中断处理程序里又草率地调用了 `EIC::steal()`,但这是不健全的,因为它违反了该类型所提供的安全不变式。即使在这个例子中它没有造成任何可见的问题,这样做也破坏了 HAL crate 和 Rust 语言所提供的安全保障。
要妥善处理这个问题,我们既可以设法让 `EIC` 中的方法保证内部同步,这样我们就能自由地共享它,甚至创建多个实例;也可以从外部保证在访问 `EIC` 时拥有独占访问权。我们将采用第二种做法,因为它更容易推广到我们可能需要与中断处理程序共享的任何其他类型,而且实现内部同步很可能本来也需要它。
我们的微控制器是单核的,因此要保证独占访问,我们只需要禁用所有中断。这样我们就能确保在访问 `EIC` 期间不会发生任何中断。访问完该类型后,我们可以重新启用中断。这段获取资源独占访问权的代码被称为临界区。
关于 ARM Cortex-M 处理器,有一点值得了解:每个中断或异常可以有不同的优先级。因此,即使在一个中断处理程序执行期间,另一个优先级更高的中断处理程序也可以触发。对于 ARMv6-M 架构,优先级从 -3(最高)到 3(最低)。NMI 和 HardFault 异常具有固定的优先级 -2 和 -1,其余异常则可配置 0 到 3 的优先级。当异常/中断处理程序执行时,执行优先级会提升到该处理程序的优先级,从而禁用所有同等或更低优先级的中断处理程序。
要禁用中断,我们将特殊寄存器 PRIMASK 设为 1。这会将优先级提升到 0。请注意,这意味着 NMI 和 HardFault 异常仍然处于活动状态,因此这些异常处理程序无法使用此机制来获取资源的独占访问权。
特殊寄存器 PRIMASK 不是内存映射的,我们需要使用 `mrs`(从特殊寄存器移到寄存器)、`msr`(从寄存器移到特殊寄存器)或 `cpsie`/`cpsid`(改变处理器状态:中断启用/禁用)指令来访问它。因此,我们自然要使用汇编来完成这件事。
# 从零开始的内嵌 Rust
为了让代码更安全,我们会把这一机制封装在一个 `critical_section` 函数里,该函数先禁用中断,运行给定的闭包,再在返回前重新启用中断。我还创建了一个 `CriticalSection` 类型,它是一枚仅在临界区内可用的唯一令牌,以及一个 `Mutex` 类型,只有在提供了对 `CriticalSection` 令牌的独占引用时,它才允许访问其内容。
我们使用特殊寄存器 IPSR 来检查当前是否不在 NMI 或 HardFault 异常处理器中,这样它们就不会破坏我们的代码不变量。同时我们读取 PRIMASK 来检查中断是否尚未被禁用,否则代码可能重新启用中断,或在另一个临界区内部再创建一个 `CriticalSection`。这两种情况下代码都会 `panic!`,将执行流转向我们在文章开头声明的 `panic_handler`13。
这些检查是使调用 `critical_section` 变得安全所必需的,但它们的缺点是会引入运行时和代码体积开销。一种替代方案是引入一个不安全的 `critical_section_unchecked`,但那样整个调用栈都会由不安全的函数组成。另一种替代方案是引入类似 `ExecutionContext` 令牌的东西,它在每个执行上下文中只可用一次,并在调用 `critical_section` 时要求提供它。
抽象就变成这样:
use core::{arch::asm, cell::UnsafeCell};
/// A mutual exclusion type, that only allows getting access to its internal /// value within a critical section. pub struct Mutex<T> { // It is unsound to get a &mut T from a &Wrapper<T> unless we use the // special UnsafeCell type. inner: UnsafeCell<T>, }
// Sync indicates that a type can be accessed concurrently from multiple // execution contexts, and Send means that a type can be sent from one // execution context to another. Mutex is only Sync when holding a type that // is Send. Rust requires the types of globals to be Sync. unsafe impl<T: Send> Sync for Mutex<T> {}
impl<T> Mutex<T> { pub const fn new(value: T) -> Self { Self { inner: UnsafeCell::new(value), } } pub fn access<'t>(&'t self, token: &'t mut CriticalSection) -> &'t mut T { let _ = token; // SAFETY: We have exclusive access to token unsafe { &mut *self.inner.get() } } }
/// A token type that proves the code is running within a critical section. pub struct CriticalSection(());
/// Runs the closure f in a critical section. This runs f with an elevated /// priority of 0, preventing concurrency with other execution contexts. /// /// # Panics /// /// Panics if called within an NMI (priority -2) or a HardFault (priority -1) /// exception handler, or if interrupts are already disabled (for example, when /// called recursively). pub fn critical_section<T>(f: impl FnOnce(&mut CriticalSection) -> T) -> T { if is_negative_priority() { panic!("critical_section cannot be called within NMI or HardFault"); }
if is_interrupts_disabled() { panic!("critical_section cannot be called recursively"); }
disable_interrupts();
let mut token = CriticalSection(()); let value = f(&mut token);
enable_interrupts();
value }
/// Returns true if currently executing the NMI (priority -2) or HardFault /// (priority -1) handler. fn is_negative_priority() -> bool { let ret: u32; unsafe { asm!("mrs {}, IPSR", out(reg) ret) } let exception_number = ret & 0x3F;
const NMI: u32 = 2; const HARD_FAULT: u32 = 3; matches!(exception_number, NMI | HARD_FAULT) }
fn is_interrupts_disabled() -> bool { let ret: u32; unsafe { asm!("mrs {}, PRIMASK", out(reg) ret) } (ret & 0b1) != 0 }
fn disable_interrupts() { // Change Processor State: Interrupt Disable (PRIMASK=1) unsafe { asm!("cpsid i") } }
fn enable_interrupts() { // Change Processor State: Interrupt Enable (PRIMASK=0) unsafe { asm!("cpsie i") } }
请注意,与我们之前写的忙等延时不同,用于禁用和启用中断的 asm! 块没有使用 options(nomem)。如果没有它,编译器必须假设这段汇编可能读写任何内存,因此它充当了编译器屏障:编译器无法将临界区内的内存访问移到临界区之外。
然后,在我们的应用程序中,我们声明一个全局静态 SHARED_EIC: Mutex<Option<EIC>>,在 main 中我们把已有的 EIC 移入这个全局变量,当我们需要访问它时,我们使用 critical_section:
static BUTTON_DOWN: AtomicBool = AtomicBool::new(false); static SHARED_EIC: Mutex<Option<EIC>> = Mutex::new(None);
#[unsafe(export_name = "EIC")] extern "C" fn eic_interrupt_handler() { let extint = SW0.extint().unwrap();
critical_section(|cs| { let eic = SHARED_EIC.access(cs).as_mut().unwrap();
eic.enable(false); // ... }); }
fn config_sw0_interrupt(port: &mut PORT, mclk: &mut MCLK, nvic: &mut NVIC) { // ...
critical_section(|cs| { let extint = SW0.extint().unwrap(); let eic = SHARED_EIC.access(cs).as_mut().unwrap(); eic.set_extint_config(extint, false, EicSensing::Low); eic.enable_interrupt(extint, true); eic.enable(true); });
nvic.enable_interrupt(NvicInterrupt::Eic, true); }
#[unsafe(no_mangle)] extern "C" fn main() { // SAFETY: Peripherals::steal() is only called here. let mut peripherals = unsafe { Peripherals::steal() };
critical_section(move |cs| { *SHARED_EIC.access(cs) = Some(peripherals.eic); });
// ... }
如果我们编译并烧录我们的应用程序,行为应该完全相同,但现在代码是安全可靠的!
结论
我们还可以探索 Rust 嵌入式开发的更多特性,比如串口通信、直接内存访问(DMA)、使用过程宏实现更安全的抽象、async Rust 等等。但这篇文章已经相当长了,我认为我们已经探讨了基础知识。
有一件事我应该说明,在使用 Rust 进行嵌入式开发时,你当然不需要像上面展示的那样从头编写一切。首先,你可以使用 cortex-m-rt crate 来初始化任何基于 Cortex-M 的微控制器,以及类似的 crate 来获得核心外设的安全封装。它还提供了过程宏,为 main 函数和中断处理程序提供了更安全的抽象。对于某些微控制器,还有完整的 HAL crate,比如 stm32-hal crate。
即使没有可用的 HAL crate,就像我的 PIC32CM PL10 的情况一样,只要厂商为微控制器提供了 SVD 文件(通常在其 CMSIS-Pack 中分发),你至少可以使用 svd2rust 自动生成外设访问 crate(PAC),它会生成访问所有外设寄存器的代码,而不是从数据手册中手动复制。它与合适的 HAL 不同,但已经提供了一个很好的起点。
如果你想了解更多关于为微控制器编写 Rust 的知识,我强烈推荐 The embedded Rust book,如果你想以与我上面介绍的相近详细程度来学习,也推荐 Embedonomicon。如果你想学习 Rust 本身,我建议你从 The official Rust book 开始。
我在这里的最终目标实际上是制作一个小型异步执行器,像 embassy 那样,以更好地探索 async Rust 在嵌入式开发中的优势,但我会把它留到另一篇文章中。