9 ms·
Writing embedded firmware using Rust
- xxpor 5y agoDamn, I've been doing a bunch of exploring of this exact topic over the past week. This would have saved me a bunch of time. Unlucky for me it wasn't submitted last Sunday! One thing that's killed me a bit is the core::/std:: split, when the core:: versions have the exact same semantics, or perhaps are equivalent for the things that they do implement (for example, the core version might be missing the serde parts, but is otherwise the same). There's a few crates I tried out that wouldn't compile with no_std, but with a simple text substitution, would work. I'm sure there's a million edge cases I'm not aware of, but if cargo or rustc could provide an option to just sub in the core version, that'd be really nice.
- eska 5y agoI assume one could send a patch to those crates that defines “use core::” instead of “use std::” by using the compile time config directive to check whether the std is enabled?
- xxpor 5y agoOh yes, and I've started preparing those patches. It's just a bit of a bummer to have the churn when you're just starting out and iterating through ideas.
- hkalbasi 5y agoIsn't "use core::" enough, without compile time config directive?
- saghm 5y agoIf you disable stuff with `cfg`, you have the ability to give cleaner error outputs. When designing a library to allow choosing between one of two dependencies for an async runtime, I conditionally compiled out all of the crate except for one of two invocations of the `compile_error!` macro (https://doc.rust-lang.org/std/macro.compile_error.html https://doc.rust-lang.org/std/macro.compile_error.html) if either both or neither of the dependencies were enabled, which I think made the experience for users of the library much better compared to having to figure out what was going on from pages and pages of "not found" or "already defined here" errors.
- nynx 5y agoYeah, std is actually just stuff re-exported from core + some more stuff.
- wyager 5y agoI recently did an embedded project using rust (https://yager.io/vumeter/vu.html https://yager.io/vumeter/vu.html). It was great, and I'm planning to use Rust for embedded projects in the future. There are a few pain points, especially around rust's relatively limited polymorphism, mutable refs, and the constraints imposed on async/await by type system limitations, but it was still super nice compared to using C(++). I'm also optimistic these pain points can be mostly fixed with improvements to the type system. I think they might already have improved length polymorphism - I think I saw something about that recently.
- sanjayio 5y agoAs someone who plans on dabbling into embedded Rust next, this is great to hear. Thanks for sharing. Any resources that were helpful in your embedded Rust journey?
- michael_j_ward 5y agoIf you're interested writing embedded Rust firmware, I suspect will also be interested in this. https://cliffle.com/blog/on-hubris-and-humility/ https://cliffle.com/blog/on-hubris-and-humility/
- NoahKAndrews 5y agoWow, what a cool system design
- bcantrill 5y agoIn addition to Cliff's talk/blog -- which are absolutely outstanding -- I would recommend listening to the Twitter Space we did on Hubris and Humility last week.[0] It was a really fun conversation, and it also serves as a bit of a B-side for the talk in that it goes into some of the subtler details that we feel are important, but didn't quite rise to the level of the presentation. And of course, be sure to check out the source itself![1][2] [0] https://www.youtube.com/watch?v=cypmufnPfLw https://www.youtube.com/watch?v=cypmufnPfLw [1] https://github.com/oxidecomputer/hubris https://github.com/oxidecomputer/hubris [2] https://github.com/oxidecomputer/humility https://github.com/oxidecomputer/humility
- travisgriggs 5y agoNaively Curious. I do quite a bit of good old C on Atmel & STMicro chips M0+ chips. When I do, there’s a whole layer/framework of register definitions (structs, enumerated, typedefs, etc) C header files that I’m able to include for my specific chip and package. If I want to experiment with Rust in place of C on one of these chips (say an Atmel SAMD21 J) what are my options? Do I have to reverse engineer all of those register mappings into Rust constructs? Can Rust import and use C header files?
- bri3d 5y agoThe embedded-hal project supplies these for a wide variety of controllers, for SAMD specifically, https://github.com/atsamd-rs/atsamd https://github.com/atsamd-rs/atsamd .
- kennywinker 5y agoTo add on to what bri3d said, these Rust register definitions are being auto-generated using SVD* files published by the chip vendors. For stm32 for example there are the auto-generated register definitions** and then the HAL layers*** on top that try to build easy to use tools on top of the registers (e.g. an SPI or USART type with write and read functions). * https://www.keil.com/pack/doc/CMSIS/SVD/html/index.html https://www.keil.com/pack/doc/CMSIS/SVD/html/index.html ** https://github.com/stm32-rs/stm32-rs https://github.com/stm32-rs/stm32-rs *** https://github.com/stm32-rs/stm32f4xx-hal https://github.com/stm32-rs/stm32f4xx-hal for the stm32f4xx line
- leafario2 5y ago> Can Rust import and use C header files? Yes, after piping them through rust-bindgen, any binary can be statically of dynamically linked. I did this, it's nice that it's possible, but the PAC route others have described here is way better.
- ahepp 5y agoI am not terribly well versed in Rust MCU development, but I poked around with the teensy-rs and esp32-rs projects a couple years ago. ARM seems to provide some XML register description files called SVDs[0]. They seem to do a decent job describing the registers and peripherals in a way that allows code generation tools to create a register access library, upon which higher level HALs can be built. For an example, you might look at the esp-rs project on GitHub. The lowest level, if I recall correctly, is the Peripheral Access Crate [1]. The README for this project describes a bit about the SVD file, and svd2rs code generation tool. Sometimes the SVD file needs to be patched to produce high quality Rust bindings. This PAC is then required as a dependency of the higher level HAL for the esp32 [2]. The higher level HAL also implements some traits from a shared Rust HAL effort [3]. I'm not really an expert in Rust so if I've described any of this wrong, someone please correct me. [0] https://www.keil.com/pack/doc/CMSIS/SVD/html/index.html https://www.keil.com/pack/doc/CMSIS/SVD/html/index.html [1] https://github.com/esp-rs/esp32 https://github.com/esp-rs/esp32 [2] https://github.com/esp-rs/esp32-hal https://github.com/esp-rs/esp32-hal [3] https://docs.rs/embedded-hal/0.2.2/embedded_hal/ https://docs.rs/embedded-hal/0.2.2/embedded_hal/
- mh7 5y agoNot seen much point in rust for embedded for small MCU's that I target. All memory are statically "allocated" as global variables/buffers and never free'd, so there's no ownership or dangling references to worry about ever. This allows me to know at link time how much memory my program uses.m and of course simplify programming. Only single cores, the only synchronization issue is between interrupts and main program, a case rust doesn't handle afaik(?) and in 99% of the cases a ring buffer or simple flag variable is enough. Never use much abstractions, so C is fine in terms of ergonomics. Never use third party libraries aside from CMSIS register headers. Probably the only thing that would help me is some static reflection and compile time programming, but I have python scripts as a code generation step to generate tables, definitions, annotations, etc, and that works fine.
- couchand 5y ago> the only synchronization issue is between interrupts and main program, a case rust doesn't handle afaik(?) and in 99% of the cases a ring buffer or simple flag variable is enough. I'm not sure what you're expecting it to handle that it isn't. That static flag or ring buffer needs synchronization and rusyc will absolutely not let you forget that (in safe code). One technique you get in Rust that's very compelling for embedded is using traits, especially when implemented on zero-sized types, to cleanly express configuration. Personally I abhor all those one-off table generating scripts.
- axegon_ 5y agoRust is a brilliant candidate for embedded systems - safety, built-in package management, it's ergonomic and pleasant to work with. But it has one fundamental problem, which the entire community refuses to address: the steep entry. Several months ago I was making a wedding gift for a friend which almost exclusively involved embedded development. And having several brand new STM32's laying around I initially opted for them and rust. In all fairness the entire thing did not involve all that much: If I recall correctly, an I2C display, RTC, sound sensor, some adafruit soundboard, sound amplifier+speaker and a couple of push buttons. I went against one of my own core philosophies of not using something for the sake of using it, that being rust on this occasion. In theory the STM32 should be a great candidate since the Embedded Rust Book revolves around it. Well... No. You see, each time you decide to get something rolling, you have to work your way through tons of configuration, completely blind. And just as you are convinced that you did everything right, compile your code and flash the device, you get a cryptic error and you are left clueless as to what it may be. It took me 7 days to get the I2C display going. I guess you could slash a few hours since I had to get Cyrillic letters out on the screen but that was just a few hours at best. At one point I simply gave up because I didn't have that much time to waste and ran back to the trusty Arduino. And this is fundamentally what's crippling the embedded Rust world - it's way too much of a hassle to be considered a good option when you have to deal with a schedule - you have to spend absurd amounts of time fiddling with setup and poor documentation. If those issues are addressed at one point, I'd gladly ditch arduino for good. But until then the embedded rust is just some fun toy to play around with on a day off.
- sanjayio 5y agoI’m curious how well you knew Rust prior to starting? I’m learning Rust at a very slow pace. I finished a language specific course, going through advent, and I’m planning on going through an embedded Rust book next. I can imagine attempting to jump straight into embedded Rust could be very challenging.
- brundolf 5y agoI get the sense they weren't talking about what most people mean when they say "steep entry" in a Rust context (i.e. the language itself), but specifically its support and documentation for the embedded case
- miohtama 5y ago> Hiring programmers proficient in Rust is much more difficult than in C or C++ due to the smaller user base. Example code, tools, and libraries released by MCU manufacturers are almost always for C or C++. The Rust embedded infrastructure is new, and rapidly changing. While Rust cost per engineer today is higher, is the cost of the project lower, because due to Rust those engineers are much more efficient?
- not_the_fda 5y agoI've been doing embedded development for over 20 years. The rust evangelists just don't understand embedded development. Embedded developers are very conservative, they don't chase the shiny and believe in using old tried and true technology. C++ offers significant benefits over C in the embedded space and its been impossible to gain traction. With C you have a HAL provided by a vendor that allows very rapid bring up of the hardware which is 90% of the battle in embedded. Switching to Rust you would have to write your own. With C you have billions of lines C libraries at your disposal to bring your product to market. To use Rust you would have to write your own or deal with the shims and lose the Rust benefits. I do 4-5 embedded projects a year, using Rust and not having the HAL and C library ecosystem would put those projects ad a competitive disadvantage. I find the whole hubris and humilty thing is ridiculous. Writing a RTOS in Rust which isn't your core competency is such a waste of resources. Use FreeRTOS and ship the product.
- jack_h 5y agoI've been in the embedded space for over 10 years so I figure I'll give my thoughts on the matter. Apologies up front as this will be a little ranty. > Embedded developers are very conservative, they don't chase the shiny and believe in using old tried and true technology. This is underselling the point. They are conservative in the same sense as an electrical engineer who refuses to use ECAD software or transistors because drafting tables and vacuum tubes are tried and true. There's a difference between "[not] chas[ing] the shiny" and just being obstinate. > With C you have a HAL provided by a vendor that allows very rapid bring up of the hardware which is 90% of the battle in embedded. Switching to Rust you would have to write your own. I'm not sure why vendor supplied HALs - which can be pretty hit or miss in terms of quality - are so important for board bring-up. In the end it's a minor milestone in the development lifecycle for all but the simplest of projects. In the projects I work on practically all of the time is spent on the complexity of the firmware and how it interacts with the various networks of sensors, actuators, cellular, BLE, storage, etc. Besides, last I checked there were many people putting effort into HALs written in Rust. > With C you have billions of lines C libraries at your disposal to bring your product to market. To use Rust you would have to write your own or deal with the shims and lose the Rust benefits. First off it has not been my experience that libraries are used often. As you mention later FreeRTOS is generally the only external code I see pulled into a project, everything else is written from scratch or copy pasted from a previous project which was written from scratch or copy pasted from a previous previous project etc. Let's assume that libraries are commonly used though, how exactly do you use them? This is one point of C/C++ that is still absolutely dire. Rust has Cargo whereas C/C++ has a lot of wacky ways to deal with it such as through git submodules, or cmake, or possibly conan. Generally speaking what I see is the code being copy pasted into the project and never updated despite the growing security concerns for connected embedded devices. Of course Rust offers more than mere package management, Cargo is also the build system, it also has support for automated testing and documentation. All of these things are typically afterthoughts at best in many embedded projects. > I do 4-5 embedded projects a year, using Rust and not having the HAL and C library ecosystem would put those projects ad a competitive disadvantage. To be clear at this point in time if I were asked if an embedded project should be written in Rust my answer would be "probably not", although given 5-10 years that answer very well may change to the affirmative. The ecosystem is young and growing; as long as the growth continues it will likely be a viable alternative in the future.
- oxidizedcutrace 5y agoLots of people pointing out that Rust isn't very ergonomic on embedded platforms. IMO one huge issue is how verbose the syntax needs to be. Look at some of the cases in the article, such as: let mut dp = pac::Peripherals::take().unwrap(); dp.RCC.ahb2enr.modify(|_, w| w.gpioaen().set_bit()); In C that would be: RCC->AHBENR2 |= RCC_AHBENR2_GPIOAEN; Okay, you only have to take ownership of the Peripherals object once, but what about when they want to set a UART register in a function? Rust wants mutable pointers to have a trail of ownership outside of 'unsafe' blocks, so now we need: pub fn setup_transmission(regs: &mut R, [...]) where R: Deref<Target = pac::usart1::RegisterBlock> { [...] regs.cr2.modify(|_, w| w.stop().bits(config.stop_bits as u8)); [...] } This is a bit of a construction, in C(++) we can just do something like: void setup_transmission([...]) { [...] USART1->CR2 &= ~(USART_CR2_STOP_BITS); USART1->CR2 |= ((uint8_t)config.stop_bits << USART_CR2_STOP_BITS_Pos); [...] } The Rust snippet seems like it would be safer in a multi-threaded environment like an RTOS, or in cases where interrupts might modify peripheral registers, but...there are so many syntactical details to remember. I really tried to like embedded Rust, and I still think it compares favorably with the sort of C HALs that most chip manufacturers distribute. But the syntax seems to get in the way of quick simple access to peripheral registers.
- m0lecules 5y agoWhy is it this way though - it seems to me like you could create a type that just works like the C code struct Uart { u8 CR2, // etc. } Instantiate it as 'static with some macro that defines where it lives in memory: #[mcu::loc(0x1002010)] static UART1 = Uart::new(); #[mcu::loc(0x1003010)] static UART2 = Uart::new(); And then have it bound directly to the memory locations on the MCU at compile time/link time. Still learning rust, so apologies if this syntax doesn't make sense.
- steveklabnik 5y agoYes, the syntax doesn't have to be this way, it's just the way that the libraries in the ecosystem tend to do it. It works, but it does also have quite a few problems, imho. But since it's just a particular library, you can write your own or use a different one.
- chana_masala 5y agoHow should I get started with writing embedded firmware period? I am a SWE but only have professional/personal experience with web development (including backend services). As a start, I have an old Chinese mp3 player that would be really neat to be able to hack and make some changes to. How would I start with that, if that's at all a good starting point.
- noisy_boy 5y agoIf your focus is to just revive/upgrade it with more features, rockbox[0] might be a choice for you. It is open source so if that works for your model, then you may be able to get to hacking quicker than doing it all by yourself (though the latter might be a lot more satisfying). [0]: https://www.rockbox.org https://www.rockbox.org
- gryph0n 5y agoAs suggested, one path is to port Rockbox firmware for your MP3 player. However, since you do not have any prior experience in embedded domain, it will not be a easy path. I would suggest that you try using the Arduino or RaspberryPI hardware. Both of these platforms are widely used, so you would be able to easily get help if you get stuck. Also, these are 'simple' platforms that are widely available, so the learning materials available is unmatched. Building a simple project like a weather station or clock will keep you focused on a "actual" target/goal. https://www.arduino.cc https://www.arduino.cc https://create.arduino.cc/projecthub/projects/tags/clock https://create.arduino.cc/projecthub/projects/tags/clock http://cactus.io/projects/weather/arduino-weather-station http://cactus.io/projects/weather/arduino-weather-station https://www.raspberrypi.org https://www.raspberrypi.org https://howchoo.com/pi/how-to-make-a-raspberry-pi-smart-alarm-clock https://howchoo.com/pi/how-to-make-a-raspberry-pi-smart-alar... https://projects.raspberrypi.org/en/projects/build-your-own-weather-station https://projects.raspberrypi.org/en/projects/build-your-own-...