Embedded Rust from Scratch
I recently got a small microcontroller, and I thought it would be a good opportunity to learn the fundamentals of ARM-based microcontrollers at a deeper level, and how to write Rust code for them.
Throughout this post, I will go over how to create a Rust application for a microcontroller without relying on any third-party solutions. I will try not to assume any prior knowledge of microcontrollers or Rust on the reader’s part, so I hope you can follow along even if you are not familiar with them (though the post will not teach you Rust).
All the code in this post can be found in this repository, and many code blocks include a direct link to a specific revision of the corresponding file.
Knowing Your Target
First thing, we need to know what kind of hardware we are targeting. In my case, I have a Microchip PIC32CM PL10 Curiosity Nano Evaluation Kit, which includes the PIC32CM6408PL10048 microcontroller, a “Nano Debugger” USB interface (for powering and accessing the debug and serial ports of the microcontroller), an LED, a button and a capacitive touch button.

The microcontroller is the main point of attention. The first thing we need to know about it is its Instruction Set Architecture (ISA). The ISA defines what instructions the microcontroller CPU is capable of running, and how they are encoded and organized in machine code.
When we compile Rust or C code to binary, it compiles down to a particular ISA. Different CPU implementations may use different micro-architectures, and may even include extra instructions and extensions on top of the baseline ISA, but the same binary will work on them regardless.
Most desktop and server computers today use the x86-64 ISA, or, more specifically, some extension of the baseline. Our microcontroller is ARM based: it includes the CPU core implementation ARM Cortex-M0+, which uses the ARMv6-M instruction set architecture (which is one of the many ISAs defined by ARM).
Besides the ISA, this core implementation also specifies some memory mapped core peripherals (like an interrupt controller, and a timer), and the microcontroller overall specifies many other peripherals (GPIO controllers, more timers, serial interfaces, etc.).
Compiling Code to ARMv6-M
By default, the Rust compiler builds for the same ISA as the platform it is currently running on. To tell the compiler to build for another ISA we need to pass a target tuple (historically called target triples) to it. The target tuple specifies not only the ISA, but the overall platform (which includes calling conventions, the binary interface, system libraries, etc.). For example, Windows and GNU/x86_64-pc-windows-msvc vs x86_64-unknown-linux-gnu).
In the case of ARMv6-M, we will use the target tuple thumbv6m-none-eabi, which targets the ARMv6-M ISA on bare metal, with no specific platform on top. We can use the --target option to tell rustc or cargo the target tuple we want to compile to.
Let’s start by setting up a minimal cargo project:
$ 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 {}
} By default Rust programs include the Rust standard library (std), which includes abstractions for doing file IO, querying time, spawning processes, etc. The target we are using does not support any of that by itself, so the standard library is not available, and we need to explicitly disable it with the #![no_std] attribute at the top of main.rs. We instead only use the core library. The main function also depends on the standard library, so we also need to disable it with #![no_main].
Instead of main, we declare a function named _start with the unsafe attribute no_mangle, to make the generated binary have a _start symbol which the linker uses as the entry point of the program1.
Footnote 1
The linker entry point is only used if the generated binary would be executed by an OS. It is not really necessary in our case, I just include it to avoid a link warning.
Rust also needs a panic_handler, which is called when the panic! macro runs (Rust’s equivalent of a runtime exception).
Then we can compile our Rust program to ARMv6-M. We first need to install the target using rustup and then pass --target to cargo build.
$ rustup target add thumbv6m-none-eabi
$ cargo build --target thumbv6m-none-eabi
With this we should have an ELF file in target/! We can use readelf and objdump to check that the file was correctly generated for our target.
First with readelf, with h for the ELF header, and A for parsing architecture specific sections:
$ 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
In the ELF header we see Machine: ARM and in the ARM attribute section we see Tag_CPU_arch: v6S-M, which refers to the ARMv6-M ISA.
To use objdump we need a version compiled with support for this architecture. The easiest way of acquiring one is by installing the llvm-tools rustup component (which includes tools with support for all targets Rust supports), and using them through cargo-binutils:
$ rustup component add llvm-tools
$ cargo install cargo-binutils
Then we can, for example, check the machine code generated for our _start function:
$ 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
We can see our function has four 16-bit ARM Thumb instructions. The instructions are saving the frame pointer (r7) and link register (lr) on the stack, updating the frame pointer to the new frame, and then jumping into the loop, which just jumps back to itself indefinitely2.
Footnote 2
If we compile with optimizations (cargo build --release --target=...) the two jumps would become one and the frame pointer update should be omitted (although in Rust 1.100, the version used in this post, rustc never omits the frame pointer on Thumb targets).
Okay, we built an ELF file with some code. But that is not enough for flashing it onto our microcontroller, much less running it.
To make it flashable we need to specify where exactly the binary data and runtime data will be mapped in memory, so that after linking, any jumps, loads and similar instructions point to the correct memory addresses, and to indicate to the programming tool where things should be written in the microcontroller flash.
Configuring the Linker
First, let’s configure our cargo project so it builds to our desired target by default, without needing to pass --target every time. We will also use this file to specify additional parameters later.
We add a .cargo/ file, specifying the build.target option:
[ build ]
target = "thumbv6m-none-eabi" Now, to tell the linker where the code, static data and runtime data should be stored and mapped, we need to create a linker script.
rustc first compiles the code to object files with relocatable code, which means all addresses the instructions refer to are just dummy addresses, and later it invokes a linker program (for this target, it is lld by default) to combine them in a single executable file, where all the code is put in different parts of memory, and all instruction addresses are resolved3.
Footnote 3
Actually, on most general purpose operating systems the code is not mapped to specific addresses. Instead, the compiler generates position-independent code, and the linker produces a position-independent executable, which can be loaded at any address. Then the dynamic loader applies relocations each time the program is loaded in memory. The OS also uses it to do address space layout randomization (ASLR), to mitigate certain vulnerability exploits. But none of that applies to the kind of microcontrollers we are targeting here.
Both the intermediate object files and the final executable file organize their content in sections, and the executable also maps those sections to segments. Later the programming tool parses those to figure out where in flash it should write them.
To explore that, let’s first make our Rust program a little more interesting:
#! [ 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 {}
} Here I just added a mutable static buffer, made entirely out of zeros, and a mutable static string reference, which is a pointer to a read-only string. I marked them with the #[used] attribute so they are not discarded as unused by the compiler and linker.
We can then compile our new executable, and use readelf -Sls (S to show sections, l for program headers/s for symbols) to see how the linker has laid out the sections:
$ readelf -Sls target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch
There are 18 section headers, starting at offset 0xea8 :
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
There are many sections, but most of them just store metadata or debug information. There are 5 sections that are actually loaded in memory, marked with the A (alloc) flag, that are mapped to one of the 3 LOAD segments in the program headers.
The .text section stores the actual machine code of the program. From the symbol table we can see that the symbol _start is at address 0x00020115, which is located inside the .text section, that starts at address 0x000201144.
Footnote 4
The addresses of _start and .text differ by one only because the least significant bit of a function pointer is set to 1 to indicate it is a Thumb state function pointer. The first instruction of _start still starts at 0x00020114, since instructions always start at an even address. ARMv6-M only supports Thumb, but some ARM architectures support both Thumb state and ARM state instructions, which is what this bit indicates.
The .rodata section stores read-only data. In our case its size is 0x10 which corresponds exactly to our 16-character string.
The .data section stores modifiable data, which in our case are the pointer (4 bytes) and length (4 bytes) of our string, so size 0x08.
The .bss section indicates modifiable data that is zero initialized. This section’s content is not actually stored in the ELF file (indicated by the section type NOBITS), it instead indicates to the operating system or the runtime to allocate/0x100, which corresponds to our 256-byte buffer, ZEROS.
There is also the .ARM.exidx, which stores unwind information, used for unwinding stack frames during the execution of a panic!, for example. Rust doesn’t support unwinding on this target by default, so we will not use this section.
After the sections, there is a list of program headers, which describe how the segments (and the sections within them) should actually be loaded in memory by the operating system, or in our case, how the programming tool loads them into flash.
Currently those sections are just being mapped to addresses around 0x00010000, 0x00020000, etc. We need to make them point to the actual memory map of our microcontroller.
If we open the datasheet for PIC32CM6408PL10048 at section 4.3 Product Mapping we can see that there is 64 KiB of Internal Flash starting at 0x0C000000, and 8 KiB of high-speed SRAM at address 0x20000000.
To pass that info to lld (and any other GNU ld compatible linker) we need to write the following linker script:
/* 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
} In the script we declare our two memory regions, declare the output sections and where they should be located. To learn more about how linker scripts work, I recommend this article by mcyoung, and the ld documentation for details.
Then we configure cargo to pass an extra option to rustc, so that it passes a flag to the linker telling it to use our linker script:
[ build ]
target = "thumbv6m-none-eabi"
[ target . thumbv6m-none-eabi ]
rustflags = [
"-C" , "link-arg=-Tlinker.ld" ,
] Running cargo clean && cargo build5 and then inspecting the generated ELF file again:
Footnote 5
cargo does not detect changes to the linker script itself, so run cargo clean to make sure.
$ readelf -Sls target/thumbv6m-none-eabi/debug/embedded-rust-from-scratch
There are 18 section headers, starting at offset 0x20e8c :
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
We can now see that .text is at address 0x0C000000, .rodata at 0x0C000008, .bss at 0x20000000 and .data at 0x20000100, as we expected.
One thing worth noting is the VirtAddr and PhysAddr columns of the segment 03 (the last LOAD segment), where the .data section is being mapped. VirtAddr stands for virtual memory address, and PhysAddr for physical memory address, or load memory address (LMA) as called by the linker. They indicate where the section is located at runtime, and where it is loaded from.
In the case of .data its virtual address is located in RAM, at 0x20000100, but its data is actually stored in FLASH, at 0x0C000028.
Anyway, now that we have everything correctly positioned in memory, we are already capable of flashing it into our microcontroller! But we still need to set up a few things to make the code actually run.
Runtime Initialization
First thing we need to know is where the CPU will first start executing code. For ARM Cortex-M based microcontrollers, the initial Stack Pointer (SP) and initial Program Counter (PC) are read from the vector table, which is read relative to the vector table offset register VTOR (see section B1.5.5 of the ARMv6-M Architecture Reference Manual). The vector table also contains the function pointer for each exception handler the microcontroller supports, like Reset (which is also the initial PC), HardFault, etc., and for each external interrupt (see B1.5.3 of the manual).
For the PIC32CM6408PL10048 in particular, on reset it runs some initialization code from the Boot ROM memory (see sections 6.4.1 and 6.5.4.5 of the datasheet), and after that sets VTOR to the start of FLASH, and loads the initial SP and PC from the vector table there. It also reserves 32 external interrupts.
So, our binary needs to have a vector table, correctly populated and positioned at the start of flash. We can update our linker script to do that:
/* then we declare our output sections, what input sections they should contain,
* and where they should be located in memory. */
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 ))
/* initial Program Counter and `Reset` exception handler.
* Points to the `_start` function */
LONG ( _start )
/* Fill the rest of Vector Table with 0s for now. This microcontroller
* reserves 32 external interrupts on top of the 15 default exceptions */
FILL ( 0x00 )
. += 4 * ( 15 - 1 + 32 );
}
/* ... */
} If we rebuild the ELF file and inspect it with readelf (-x .vector_table to dump its content):
$ 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)
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 : 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
Hex dump of section '.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 ................
We can see that .vector_table is positioned at 0x0c000000 and its hexdump contains 0x20002000 and 0x0c0000c1 (the bytes are reversed due to little-endianness), which is the end of SRAM and the value of the _start symbol, respectively.
The last thing we need to do is some runtime initialization. High-level languages, like C and Rust, require a minimal runtime for their code to work, which is commonly provided by the operating system, system libraries, the standard library, etc. We don’t have any of that here so we need to do it ourselves. Fortunately, just initializing the RAM as the sections .bss and .data describe is enough for what we are doing.
Because any Rust code already assumes that its runtime is initialized, we cannot use it to initialize the runtime. Nor any other high-level language for that matter. We need to use assembly code instead. Thankfully we can write assembly inside Rust itself by using core::arch::asm! and core::arch::global_asm!.
First, we need to update the linker script to declare some symbols that mark the start and end of each section. I will also be using load (ldr) and store (str) instructions to initialize the sections in 4-byte chunks, and those instructions only allow aligned addresses, so we also need to ensure these sections are 4-byte aligned.
The linker script then becomes:
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 ); We then replace the existing fn _start() function with the following global_asm! call:
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
"#
}
# [ unsafe ( no_mangle )]
extern "C" fn main () {} In the above code we use assembly to define the _start routine, which zeroes the .bss section, copies the .data from FLASH to SRAM, and finally calls fn main.
We need to add the #[unsafe(no_mangle)] attribute so this function generates a symbol named exactly main, and extern "C" to specify its calling convention. The calling convention defines what machine code needs to do to call the function. By default, Rust functions use an unstable calling convention, so we instead specify it to use the C calling convention, which is stable per target, so we can know the assembly required to call it. In this simple case, just running the branch-and-link (bl) instruction is enough.
Ok, now we can finally write some application code inside main!
# [ unsafe ( no_mangle )]
extern "C" fn main () {
// let's, uh, compute the Fibonacci sequence!
let mut a = 1 ;
let mut b = 1 ;
for _ in 0 ..10 {
( a, b) = ( b, a + b);
}
}
…but, unless you are satisfied with imagining that the CPU is doing something, flashing this kind of code is not that different from doing nothing at all. We need to make the microcontroller do something actually visible.
Blinking an LED
In the world of embedded software development, the equivalent of a Hello World program is a program that blinks an LED. You could also print a Hello World but you would need to have at least a serial interface working before that. Blinking an LED requires much less.
My board includes an LED, named LED0, connected between pin PB02 of the microcontroller and the MCU voltage source, with a 1 kΩ resistor in series. So, if we configure that pin to a low voltage level, the LED should conduct current and light up, and turn off on a high level.
To control the pin voltage level this microcontroller has the PORT peripheral (see section 27 of the datasheet). It allows configuring how each pin of the microcontroller behaves.
To access this peripheral on this microcontroller we need to make use of Memory-Mapped Registers, more generally known as Memory-Mapped Input/
If we look again at section 4.3 Product Mapping we can see that the PORT peripheral is mapped to memory starting at address 0x41000000. From section 27.6 we can see the offset of each register of PORT. The PORT has two groups of registers called A and B, each with its own duplicated set of registers, controlling its own group of pins.
We can use the DIR register to control if the pin should be input (allows reading an external digital signal) or output (allows driving a voltage level out), and OUT to define what voltage level it should drive.
From the pin name “PB02” we know it is the third pin of the second PORT group. So we need to access bit 2 of the registers DIR and OUT of the second group of PORT registers. Group B is at offset 0x80, and DIR and OUT are at offset 0x00 and 0x10, respectively, so we need to access 0x41000080 and 0x41000090.
In Rust that would be:
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 );
}
}
We create pointers to each register by casting its literal address to a raw pointer, and store them in consts. We then use write_volatile to set bit 2 of DIR01 as 1, and the corresponding bit of OUT01 as 0. That should make the LED turn on. We need to use write_volatile here because those writes generate side-effects in the hardware, otherwise the compiler assumes writes have no side-effect and may optimize them away.
Also note that we are using raw pointers, which have no guarantee of validity, so writing to them is an unsafe operation in Rust. We need to wrap them in an unsafe block and manually verify that the operation is actually correct (or in other words sound).
In Rust the use of unsafe code is strongly discouraged unless absolutely necessary. So requiring it every time we need to change a pin output level would be very bad. We will later explore how we can encapsulate that unsafety away behind a safe abstraction we can reuse.
But for now, we can use the following code to blink our 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),
);
}
} It sets the PB02 direction as output, then toggles the output level between 0 and 1 every second. I also used some assembly to decrement a counter 1.33 million times, which should be 1 second of delay at the CPU clock frequency of 4 MHz6.
Footnote 6
4 MHz is the default clock frequency when exiting boot, but it is also possible to configure it up to 24 MHz, which would impact this delay code.
Now we finally have a program worth flashing onto our device!
Flashing Our Code
The flashing method varies between devices. The microcontroller could have a boot ROM code that reads flashing instructions from a serial interface or USB, or it may have dedicated pins for flashing, or it may read code directly from an external flash device.
ARM based microcontrollers, like our PIC32CM, normally have dedicated pins that give access to its On-Chip Debugger (OCD), that allows debugging and flashing the device. Our microcontroller uses the Serial Wire Debug (SWD) interface (a standard interface defined by ARM) that consists of two wires, SWDIO (data) and SWCLK (clock). To make use of it, it is required to connect those signals (plus GND, VCC and RESET) to a debugging probe device, like a J-Link.
Fortunately many development kits, including mine, come with a built-in debugging probe that provides a USB interface to the microcontroller’s debug interface. My board includes a Microchip Nano Debugger debugging probe, which provides a CMSIS-DAP interface.
CMSIS is a set of tools and standards defined by ARM to provide more consistent support across all ARM devices. The CMSIS-DAP standard defines the communication interface with a debug probe, so any compatible programming tool should be able to communicate with any compatible debug probe. So there are many tools that would allow us to flash our device, like the ones provided by Microchip itself, or open source tools like OpenOCD, pyOCD and probe-rs.
Unfortunately, despite the debugging probe itself following a standardized protocol, each microcontroller has a different interface to its internal flash, which then requires a different flash algorithm. Therefore, the tool often requires custom support for each microcontroller family. From what I saw, none of the open source tools I mentioned above had built-in support for the PIC32CM PL10 family (most developers just use the vendor-provided tools, and it is a relatively new family released this year, so I am not surprised).
But fortunately, ARM also established the CMSIS-Pack specification, which is basically a zip file that distributes documentation, debug sequences, flash algorithms, device headers, etc., which in theory should provide everything you need to use a microcontroller. pyOCD can parse those packs to get support for a microcontroller, so a lot of times it does not require built-in support for it to work. This works for flashing my PIC32CM6408PL10048, but it does not work 100% (I didn’t test it a lot, but debugging via gdb for example didn’t work).
I myself added support for my microcontroller to probe-rs, and that is what I will be using in this post. probe-rs is a debugging toolkit developed by the embedded Rust community, with better integration with Rust, so I found it appropriate to use it here.
After following the installation (I had to install from source to get the support I just added) and setup instructions, we can connect our device to the PC via USB, and check that it is recognized:
$ 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.
And we can finally flash our program to our device:
$ 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)
And then we can see that the LED turns on and off every second!
Also, probe-rs installs a cargo-flash binary, so it allows us to build and flash our program with a single command:
$ 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)
Adding Safe Abstractions
As I mentioned earlier, we are using unsafe operations to access the registers of the PORT peripheral. In Rust, an operation is considered unsafe if it has any preconditions that, when violated, may compromise memory safety, or in general cause any form of undefined behavior. For example, dereferencing a raw pointer has the precondition that the pointer is valid.
To make things safer we can wrap the unsafe operations in a function. The function may then use extra checks or the type system to ensure that the preconditions of the unsafe operations are upheld, and be considered safe. But if the function doesn’t ensure all preconditions, the function is considered unsafe, and should be marked as such, hopefully accompanied with documentation on what must be upheld to safely call it.
For our application we could create, for example, a function for turning our LED on or off:
/// 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);
}
}
This function reads the current value of DIR and OUT, updates the bit corresponding to our LED, and writes the value back. Then our main function would become:
# [ unsafe ( no_mangle )]
extern "C" fn main () {
let mut toggle: bool = false ;
loop {
toggle = !toggle;
unsafe {
set_led0 ( toggle);
}
delay_1s ();
}
}
Notice that this function is still unsafe7, because it does a non-atomic operation on those registers8. If another piece of code runs concurrently between a read and its corresponding write (here it would be an interrupt), and that other piece of code updates another bit of the register, that update would be discarded when the write then executes.
Footnote 7
This function is not necessarily unsafe. This code is specific to our microcontroller, on which the reads and writes performed here are atomic, so Rust memory safety is not violated, as race conditions are not considered unsafe per se (see Data Races and Race Conditions). But this kind of race can cause some safety invariants relied upon by another piece of unsafe code to not hold, in which case the function would be unsound, and the race could be considered a data race.
Footnote 8
This PIC32 also has the DIRSET, OUTCLR, OUTSET and other registers that would allow implementing this function without a read-modify-write non-atomic operation, but I chose this implementation for the sake of example.
This would be a data race. But Rust was built to make exactly this kind of bug impossible. The main problem here is that the PORT registers are globally accessible, so we need a way to coordinate the access to them so it is never done concurrently. If we achieve that, we can remove the unsafe mark from the function, making all callers of the function safe.
We could introduce a runtime check using a Mutex lock or something, but we can do better. We can use the Rust type system to make PORT no longer globally accessible, then use the usual Rust borrowing mechanisms to make every access safe, with zero runtime overhead. First we create a type PORT, representing our peripheral, in a new module named port:
mod port; /// Interface for the PORT Peripheral.
pub struct PORT (()); struct PORT(()) is a tuple struct with a single private field of type (), the unit type. The field type is not important, what is important is that its field is private, so this type cannot be constructed outside of this module.
Then we add a public method for creating this type:
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 (())
}
} Then we update our previously unsafe function to:
/// SAFETY: must only be accessed if holding `&mut PORT`.
const DIR01 : * mut u32 = 0x41000080 as * mut u32 ;
/// SAFETY: must only be accessed if holding `&mut PORT`.
const OUT01 : * mut u32 = 0x41000090 as * mut u32 ;
/// Set LED0 On or Off.
fn set_led0 ( _port : & mut PORT , on : bool ) {
// SAFETY: we have an exclusive reference to `PORT`
// so it is safe to access PORT registers.
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);
}
} The PORT type is designed in such a way that only a single instance of it exists at a time. This property should be guaranteed by whoever calls PORT::steal(), so this function is unsafe.
Then later set_led0 receives a &mut PORT. In Rust, &mut PORT means exclusive reference to PORT, that means that Rust guarantees, in its language semantics, that set_led0 is the only function that has an active reference to the single instance of PORT, hence it is totally sound to access DIR01 and OUT01, as any other execution context (like an interrupt handler) cannot be also holding a reference to PORT.
Main then becomes:
mod port;
use crate :: port:: PORT ;
// Declare the `main` function the code above calls into.
# [ 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 ();
}
} Our application only needs to use unsafe once to get an instance of PORT, then later all accesses to its registers are safe!
Full(ier) PORT Abstraction
Of course the previous code is very contrived, you would never expose a safe abstraction for only a single pin. The natural path is to make an abstraction that models the entire PORT peripheral.
First we can declare some structs to represent the register block:
# [ 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 ],
} Notice that we use the attributes repr(C) and repr(C, align(0x80)) to make sure the fields are laid out in memory with the exact offsets of the registers in the real hardware peripheral. Without repr(C), Rust is allowed to reorder the fields to optimize the struct layout (or for any other reason).
Then we update our PORT type with methods and types that give a safe and convenient abstraction over the PORT peripheral.
# [ 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 ,
};
// etc...
}
/// Interface for the PORT Peripheral.
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 (())
}
/// 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.
const fn ptr ( & mut self ) -> * mut PORTRegisterBlock {
0x41000000 as * mut PORTRegisterBlock
}
/// Return Group of index N of PORT control registers.
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);
}
} We could expose a lot more features of the PORT peripheral, but the code above is already enough for us.
Note that we marked PORT with pub but not PORTRegisterBlock and the method PORT::ptr(). That means that only PORT and its public methods are visible outside the module, so the rest of the application code cannot accidentally circumvent the safety abstraction we built9.
Footnote 9
It is worth pointing out that making the registers inaccessible as shown here may not be the best practice for a publicly shared library, as it makes it a lot harder for downstream users to work around any limitation of the provided abstractions.
Finally our application function becomes as simple as:
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);
} Now our main application code has zero unsafety! I mean, besides the unsafe { PORT::steal() }. We could make a safe wrapper around steal() by adding a runtime check, but since ARMv6-M has no atomic compare-and-swap instruction, doing that safely requires establishing a critical section (which we will see later).
A HAL Crate
In order to have a better separation between what is hardware abstraction code and what is application code, we can move our hardware abstraction code to another crate (a crate is, basically, a Rust library10).
Footnote 10
To be pedantic, a Rust crate is a unit of compilation of the Rust language. It can either be a library crate or a binary crate. A Cargo.toml manifest defines a Rust package, which can contain at most one library crate, and any number of binary crates. A Cargo dependency is another package that contains a library crate, which your code links against.
We can first edit our root Cargo.toml to define a workspace:
[ workspace ]
[ package ]
name = "embedded-rust-from-scratch"
version = "0.1.0"
edition = "2024"
[ dependencies ] We can then create our new crate, and add it as a dependency of the root 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
Our Cargo.toml then becomes:
[ 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" } Here hal stands for hardware abstraction layer (HAL), a common term in embedded software.
Then we can move port.rs to pic32cm6408pl10-hal/, and the global_asm! and mod port code from src/ to pic32cm6408pl10-hal/. We also need to add pub to mod port and add #![no_std] at the top of lib.rs.
At the end:
#! [ 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
"#
} Now any hardware abstraction we add in the future goes to the pic32cm6408pl10-hal crate, and we can share this crate across projects. We could make it extra shareable by also moving the linker.ld linker script to the HAL crate, but that would require some extra setup (see the cortex-m-rt crate as reference).
Timer and Interrupts
Okay, we now have somewhat safe application code for our microcontroller. Next, let’s improve our delay_1s function. Currently it just busy-loops decrementing a counter. A more efficient way of doing this is by using a timer peripheral. Using one avoids keeping our CPU busy during the delay, which would allow us to do some other work concurrently with the timer, or just halt the CPU and save some power.
In this microcontroller we have a couple of timer peripherals to choose from:
- the ARMv6-M core peripheral SysTick,
- 3 TC (Timer/
Counter) peripherals, - 1 TCC (Timer/
Counter for Control Applications) peripheral, and - 1 RTC (Real Time Counter) peripheral.
Each timer has a different counter register size (from 8-bit to 32-bit, plus prescalers) and set of functionalities (waveform generation, input capture, calendar mode, more interrupt events, etc.). Since we will use the timer just for simple delays, the SysTick timer is enough and is also a timer that many Cortex-M microcontrollers have, so learning it is more transferable.
The ARMv6-M SysTick timer is a simple 24-bit counter. It basically has 3 registers:
- Status and control register (SYST_CSR): allows enabling the timer and its exception, changing the clock source, and reading a “has counted to 0” flag.
- Reload value register (SYST_RVR): every time the timer counts to 0 it wraps back to this value.
- Current value register (SYST_CVR): returns the current count on read, and resets the counter to 0 on write.
It also has a calibration register that optionally contains a reference reload value for 10 ms timing, plus info like whether an external reference clock is implemented. But those are not available in the PIC32CM PL10.
Based on that we can already create an abstraction for 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 ),
)
}
}
/// Write the Reload Value Register.
///
/// `value` should fit in 24 bits.
pub fn write_reload_value ( & mut self , value : u32 ) {
unsafe {
let reg = & raw mut ( * self . ptr ()). syst_rvr ;
reg. write_volatile ( value);
}
}
/// Return the current count.
pub fn current_count ( & mut self ) -> u32 {
unsafe {
let reg = & raw mut ( * self . ptr ()). syst_cvr ;
reg. read_volatile ()
}
}
/// Resets the Counter to 0.
pub fn reset_counter ( & mut self ) {
unsafe {
let reg = & raw mut ( * self . ptr ()). syst_cvr ;
reg. write_volatile ( 0x0 );
}
}
}
// See Table B3-13 in "ARMv6-M Architecture Reference Manual"
# [ repr ( C )]
struct SysTickRegisterBlock {
/// Control and Status Register (SYST_CSR)
///
/// | Bit(s) | Name | Function |
/// | --- | --- | --- |
/// | 16 | COUNTFLAG | Set to 1 on count to 0. Clear on read. |
/// | 2 | CLKSOURCE | Always 1. |
/// | 1 | TICKINT | 1 enables SysTick exception. |
/// | 0 | ENABLE | 1 enables the counter |
syst_csr : u32 ,
/// Reload Value Register (SYST_RVR)
///
/// | Bit(s) | Name | Function |
/// | --- | --- | --- |
/// | 31:24 | Reserved |
/// | 23:0 | RELOAD | Value loaded in SYST_CVR after reaching 0.
syst_rvr : u32 ,
/// Current Value Register (SYST_CVR)
///
/// | Bit(s) | Name | Function |
/// | --- | --- | --- |
/// | 31:24 | Reserved |
/// | 23:0 | CURRENT | Current counter value |
syst_cvr : u32 ,
/// Calibration Value Register (SYST_CALIB)
///
/// | Bit(s) | Name | Function |
/// | --- | --- | --- |
/// | 31 | NOREF | Always 1 - reference clock not implemented |
/// | 30 | SKEW | Always 1 - calibration value inexact |
/// | 29:24 | Reserved |
/// | 23:0 | TENMS | Always 0 - No calibration value provided |
_syst_calib : u32 ,
} We can also create a Peripherals wrapper type over all peripherals of the HAL crate, so the application code needs to do only a single unsafe call, instead of one per peripheral:
/// Interface for all Peripherals.
pub struct Peripherals {
pub port : PORT ,
pub sys_tick : SysTick ,
}
impl Peripherals {
/// Create a new `Peripherals`.
///
/// # Safety
///
/// This method should only be called once.
pub unsafe fn steal () -> Self {
Self {
port : unsafe { PORT :: steal () },
sys_tick : unsafe { SysTick :: steal () },
}
}
} We can then rewrite our main code as:
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: Peripherals::steal() is only called here.
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 ) {
// Main clock is at 4MHz
sys_tick. init ( 4_000_000 , false );
while !sys_tick. has_counted_to_zero () {}
// Stop the timer
sys_tick. write_control ( false , false );
} Nice! We are still busy-looping in while !sys_tick.has_counted_to_zero() {}, but we could now run some other code inside that loop without messing with our time counting. Or, we could instead execute a Wait for Interrupt (WFI) or Wait for Event (WFE) instruction to make our microcontroller enter a lower power mode until the timer triggers an interrupt.
For that to work we need to implement the SysTick exception handler, otherwise our code crashes when the interrupt happens. Let’s also take this opportunity to properly fill in the whole vector table.
Previously we implemented only the initial stack pointer and the Reset exception handler, directly in the linker script. We can instead make an array in Rust with all exception handlers, put it in a special section, and then use the linker to put it in the correct place.
// 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 },
]; I also renamed the symbol _start to Reset in the global_asm! block in lib.rs, to match the exception name. Then in the linker script:
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 ) We use the KEEP statement because rustc passes --gc-sections to the linker by default, which makes it drop any section with no symbol inside it being referenced. Notice that in the Rust code we only declare each symbol inside an extern block, but don’t actually implement them. That is so we can implement the interrupt handlers from the application.
Another thing to notice is that we are using extern "C" as the ABI of those functions. That is because in the ARMv6-M architecture, the C ABI and the ABI that the processor itself uses to call the interrupt handler are the same. They are not always aligned, in which case we would have to write a trampoline function in assembly to make it work.11
Footnote 11
Some ARM exception handlers pass some extra info in registers or on the stack. They are still compatible with the calling convention, but a trampoline is required to access that info.
The way it is now, the application code would need to implement all interrupt handlers, otherwise an “undefined symbol” error would happen on linking. To avoid that we can adjust our linker script to provide a fallback implementation. First we define that default handler in our HAL crate:
# [ unsafe ( export_name = "DefaultExceptionHandler" )]
unsafe extern "C" fn default_exception_handler () {} Then in the linker script we can use the PROVIDE statement to make this exception handler be the fallback symbol for any undefined exception handler. When the application code actually provides the interrupt implementation, the PROVIDE statement has no effect:
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 ); For our application, the default interrupt handler is enough as we just want to wait for the interrupt to happen, and the peripheral already has a flag for when the timer has reached zero. Now our application code becomes:
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 " ) }
} With this, the microcontroller should now be drawing less power12!
Footnote 12
According to the datasheet, it should go from ~5 mA of current to ~1 mA, considering that I am using the internal clock source. But the datasheet only provides values for 24 MHz, and we are running at the default of 4 MHz, so it is probably considerably less than that. I would measure it myself, but it requires some hardware modifications to the devkit.
Reading Buttons
Okay, next thing we will do is wait for a button press using interrupts. My board has a button named SW0 connected to pin PB03. When the button is open (not pressed) the pin floats and when it is closed (pressed) the pin is connected to GND with a 1 kΩ series resistor. To make it not float when open we need to enable the microcontroller pin’s pull-up resistor.
Let’s start by just reading the button using the PORT peripheral, before setting up the interrupts. To read a pin we need to not only configure DIR as input, but enable the input buffer in PINCFG, and then read the value from IN. We also need to enable the pull-up in PINCFG, which only works when OUT is set to 1.
For that we need some extra methods in our PORT type:
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 );
// etc...
}
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
}
}
// ...
} Then we can modify our main to, for example, make the LED blink faster while the button is being pressed.
// Low level means pressed
const SW0 : PortPin = PortPin :: PB03 ;
# [ unsafe ( no_mangle )]
extern "C" fn main () {
// SAFETY: Peripherals::steal() is only called here.
let mut peripherals = unsafe { Peripherals :: steal () };
let port = & mut peripherals. port ;
let sys_tick = & mut peripherals. sys_tick ;
// Config 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 ) {
// Main clock is at 4MHz
sys_tick. init ( ms * 4_000 , true );
while !sys_tick. has_counted_to_zero () {
wait_for_interrupt ();
}
// Stop the timer
sys_tick. write_control ( false , false );
} We could have a higher-level pin configuration abstraction to avoid requiring our application code to keep those 3 registers in sync, but it is enough for now.
If we test our application now, we can see the LED blinking fast when we press the button!
But notice one problem: we only read the button input once per toggle, right after toggling the LED, so if we press the button right after the LED toggles we may need to wait up to 1 second for the application to detect the press. To avoid this, we need to configure pin interrupts.
Handling Pin Interrupts
For interrupts to work we need to get a few more peripherals working:
- Nested Vectored Interrupt Controller (NVIC): this is an ARM core peripheral, which allows enabling interrupts, and setting their priority.
- External Interrupt Controller (EIC): allows configuring interrupts for EXTINT lines, like enabling edge or level detection, and filtering.
- Main Clock (MCLK): Allows enabling individual clock signals for each peripheral. We need to enable the one for EIC.
- PORT: we need to add support for pin multiplexing, which will allow connecting our PB03 pin to the EXTINT[3] line.
Here is the code for each peripheral:
pub struct MCLK (());
impl MCLK {
/// Create a new `MCLK`.
///
/// # Safety
///
/// This method should only be called if no other instance of `MCLK`
/// 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 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 ;
// Enable or disable the EIC
ctrla. write_volatile (( enable as u8 ) << 1 );
// wait for SYNCBUSY.ENABLE, so enable-protected registers (like
// CONFIG) are only written after the EIC is actually disabled.
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 ;
// configure pin-sensing.
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 ;
// read pin-sensing configuration.
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 ),
)
}
}
/// Enables or disables the interrupt for EXTINTn, where n is `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);
}
}
}
/// Clears the interrupt flag for EXTINTn, where n is `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 (()),
})
}
} And our new PORT API for configuring the pin multiplexer:
# [ 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 );
// etc...
/// Returns the number of the associated EXTINTn line, if any.
///
/// See section 2.3. "Pinout and Multiplexing" of the datasheet.
pub fn extint ( & self ) -> Option < u8 > {
Some ( match * self {
Self :: PB02 => 2 ,
Self :: PB03 => 3 ,
// etc...
_ => 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),
);
}
}
// ...
} We also add mclk, eic and nvic fields to our Peripherals struct.
Then in our application code we enable the peripheral multiplexer for our pin, set its peripheral function to EXTINT[3], enable the clock for EIC, configure EIC to interrupt on level low of EXTINT[3], and finally enable EIC interrupts in NVIC:
fn config_sw0_interrupt (
port : & mut PORT ,
mclk : & mut MCLK ,
eic : & mut EIC ,
nvic : & mut NVIC ,
) {
// config SW0 as pull-up input, connected to 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 );
// enable EIC clock
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 );
} We use level detection because edge detection requires the EIC to be clocked by a generic clock (GCLK), which would be yet another peripheral to configure.
With this, if you press the button the EIC interrupt flag should activate, making the microcontroller jump to the interrupt handler!
But if we do nothing in the interrupt and just return from it, the interrupt flag will continue to be active, so the interrupt will trigger again, even if we release the button, effectively freezing the microcontroller.
So we need to override the default interrupt handler with one that clears the pending flag of the EIC peripheral. We also need to invert the interrupt from level low to level high. This way it only interrupts again when the button is released.
And we can also set a global variable to keep track of the button state so we can read it from main after each wait_for_interrupt. We use an AtomicBool for that, because a global shared between main and an interrupt handler can only be safely modified through a shared reference if it has some form of synchronization (a static mut would require unsafe on every access). ARMv6-M has no atomic read-modify-write instructions, but atomic loads and stores are all we need here, and Ordering::Relaxed is enough, since we don’t use the flag to synchronize access to any other data.
At the end the code becomes:
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 ();
// calling `EIC::steal()` here is unsound!
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 );
}
} Now the LED starts blinking fast exactly when the button is pressed!
Critical Sections
One problem though: we need access to a &mut EIC from the interrupt handler, but it is only available in main. I just hackily call EIC::steal() again in the interrupt handler, but that is unsound, as it violates the safety invariant that the type provides. Even if it does not cause any visible problem in this case, doing so undermines the safety guarantees provided by the HAL crate and the Rust language.
To properly handle that, we could either make the methods in EIC guarantee internal synchronization, so we can freely share it and even make multiple instances of it, or we can externally guarantee exclusive access to EIC when accessing it. We will do the second one, as it is more easily translated to any other type we may need to share with an interrupt handler, and implementing internal synchronization would likely require it anyway.
Our microcontroller has a single core, so to guarantee exclusive access we just need to disable all interrupts. That way we can be sure that no interrupt will happen while accessing EIC. After we finish accessing the type, we can re-enable the interrupts. This section of code that acquires exclusive access to a resource is called a critical section.
One thing worth knowing about ARM Cortex-M processors is that each interrupt or exception may have a different priority level. So even during an interrupt handler another interrupt handler of greater priority can trigger. For an ARMv6-M architecture, the priority levels go from -3 (highest) to 3 (lowest). The NMI and HardFault exceptions have fixed priorities of -2 and -1, and the rest have a configurable priority from 0 to 3. When an exception/
To disable interrupts we set the special register PRIMASK to 1. This increases the priority level to 0. Note that this means that the NMI and HardFault exceptions are still active, so those exception handlers cannot use this mechanism to acquire exclusive access to the resource.
The special register PRIMASK is not memory mapped, instead we need to use the
instructions mrs (move to register from special register), msr (move to
special register from register), or cpsie/cpsid (change processor state:
interrupt enable/
To make things safer, we will encapsulate this mechanism inside a critical_section function that disables the interrupts, runs the given closure, then enables the interrupts again before returning. I also created a CriticalSection type, which is a unique token only available inside the critical_section, and a Mutex type that only gives access to its content when an exclusive reference to the CriticalSection token is provided.
We use the special register IPSR to check if we are not in the NMI or HardFault
exception handlers, so they don’t break our code invariants. And we read PRIMASK
to check if the interrupts are not already disabled, otherwise the code may
re-enable the interrupts or create a second CriticalSection while inside another
critical section. In both cases the code panic!s, diverting the execution to
the panic_handler we declared at the start of the post13.
Footnote 13
Those checks are required to make calling critical_section safe, but they have the disadvantage of introducing runtime and code size overhead. One alternative would be to introduce an unsafe critical_section_unchecked, but then the entire call stack would be made of unsafe functions. Another alternative would be to introduce something like an ExecutionContext token that is available only once per execution context, and require it when calling critical_section.
The abstraction becomes like this:
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 " ) }
} Notice that, unlike the busy-loop delay we wrote earlier, the asm! blocks that disable and enable the interrupts don’t use options(nomem). Without it, the compiler must assume that the assembly may read and write any memory, so it acts as a compiler barrier: the compiler cannot move the memory accesses inside the critical section to outside of it.
Then in our application we declare a global static SHARED_EIC: Mutex<Option<EIC>>, in main we move the EIC we have to this global, and when we need to access it we use a 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 );
});
// ...
} If we compile and flash our application, the behavior should be exactly the same, but now the code is safe and sound!
Conclusion
We could explore many more features of embedded development in Rust, like serial communication, Direct Memory Access (DMA), using procedural macros for safer abstractions, async Rust, etc. But this post has already gotten pretty big, and I think we have already explored the fundamentals.
One thing that I should make clear is that, when doing embedded development with Rust, you of course don’t need to write everything from scratch as shown above. For a start you can use the crate cortex-m-rt for initializing any Cortex-M based microcontroller, and similar crates to get safe wrappers for the core peripherals. It also provides procedural macros that give a much safer abstraction for the main function and interrupt handlers. There are also full HAL crates for some microcontrollers, like the stm32-hal crate.
Even if no HAL crate is available, as was the case for my PIC32CM PL10, you can at least automatically generate a peripheral access crate (PAC) using svd2rust, which generates code to access all peripheral registers, instead of manually copying them from the datasheet, as long as the vendor provides an SVD file for the microcontroller (usually distributed inside its CMSIS-Pack). It is not the same as a proper HAL, but already gives a good head start.
If you want to know more about writing Rust for microcontrollers, I highly recommend The embedded Rust book, and also the Embedonomicon if you want to learn it at around the same level of detail that I cover above. If you want to learn Rust itself, I recommend you start with The official Rust book.
My final goal here was to actually make a little async executor, like embassy, to better explore the strengths of async Rust for embedded development, but I will leave that for another post.