r/embedded • • 5h ago

Embedded Rust from Scratch

https://rodrigodd.github.io/2026/12/05/rust-embedded-from-scratch.html

I recently got a small microcontroller, and I thought it was a good opportunity to learn more about how ARM-based microcontrollers work under the hood and how Rust works on embedded devices. In this blog post, I go over how to implement a very basic example application in Rust from scratch, covering everything from runtime initialization to how to build memory-safe abstractions for peripherals.

Hopefully, preexisting knowledge of Rust is not required to follow the post.

1 Upvotes

2 comments sorted by

1

u/Simple_Tough4223 1h ago

Nice post, and thanks for writing it from scratch. Most Rust embedded tutorials start with cortex-m-rt and a PAC, so it's good to see the linker script and runtime init explained step by step.

A few questions:

- For the safe PORT/HAL abstraction, how did you decide where unsafe stays? Is it only the register access, with the pin type-state on top of it?

- For the critical sections with the pin interrupts, did you just disable interrupts (PRIMASK), or something finer? On Cortex-M0+ there is no BASEPRI, so I'm curious how you share data between the ISR and main.

- Did you check the generated code with optimization on, to see how much the abstractions cost compared to writing the registers directly?

Looking forward to the rest of the series if you continue, e.g. UART or DMA on this board.

1

u/Rodrigodd_ 17m ago

Thanks!

  • Yes, I wrote the minimum code necessary to keep things memory safe, which is just abstracting over the unsafe pointer dereferences and avoiding concurrent access to the peripherals. So no hardware semantics are considered unsafe here. Pin type-states could naturally be built on top of the code presented, with no extra unsafety required.

  • Yes. I am not familiar with BASEPRI, I only learned what was available on the Cortex-M0+ for the post. But I guess doing anything finer, with multiple priority levels and such, would require a more sophisticated abstraction.

  • No, I did not, but I had previously checked that arguments that are references to zero-sized types (like &mut PORT) are optimized away, so they should not emit too bad code. Taking a quick look at the generated code with a --release build, all register accesses appear to compile down to plain loads/stores at fixed addresses.

I am planning to cover just building an async Rust executor, which I think will already be a big post by itself. But I will think about how SERCOM+DMA could fit here, I was planning to simply use rtt crate, just to make debugging and demonstrations easier.