Can Rust work on microcontrollers?

Can Rust work on microcontrollers just like C?

Yes

4 Likes

There’s no theoretical reason it can’t.

Rust allows you to poke at arbitrary memory addresses with volatile loads and stores, just like C. It’s considered unsafe, since Rust can’t account for the effects of memory mapped I/O.

Rust compiles into straight assembly, with jumps, pointers, arithmetic instructions, a call stack, a data stack, and a heap store. Also just like C.

Rust allows you to compile without the filesystem or other OS facilities, which is probably something you want on a tiny microcontroller with no OS.

But

Rust’s compiler only supports CPU architectures that it has been made to support. It’s been ported to the AVR, and made to run in the Arduino. It’s been ported to a few other stuff, too. But it’s not been ported to as many platforms as C.

5 Likes

So since we are using unsafe for microcontrollers, is there a benefit of using Rust over C if we are using it on a supported architecture?

Yes. Follow the link @dcarosone posted! The top section of that page answers that specific question.

1 Like

Oh thanks then.

unsafe doesn’t remove Rust’s protections; instead it tells the compiler that for specific aspects of the code, the compiler should trust that the programmer has not broken a predefined, limited subset of those protections, rather than the compiler insisting that it be able to prove on its own that each of the relevant compiler requirements has not been broken.

2 Likes

There has been a good talk about what benefits you gain from using Rust on a µC at last Rust Conf (https://www.youtube.com/watch?v=t99L3JHhLc0&index=5&list=PL85XCvVPmGQi3tivxDDF1hrT9qr5hdMBZ).

3 Likes

Rust is using unsafe for arbitrary memory access on all platforms, libstd just abstracts it away from you.

1 Like

As does the embedded-hal (and similar) frameworks in the embedded ecosystem. I’ve not written a single unsafe anywhere in an embedded project for stm32.

4 Likes

@japaric’s Brave New I/O is a great read to show how Rust’s owernship model can be used to protect more than memory safety - also resource/IO usage.

6 Likes

One question, is an Arduino a microcontroller?

Yes, it is, but is recommend for only education, because you can t sell a product with the arduino

That's incorrect statement. Read more here: https://www.arduino.cc/en/Main/FAQ#toc10