RUST
Runing Rust on the Raspberry Pi
David Bolton continues looking at Rust development with SDL2 but now he’s doing it on a Raspberry Pi of all places!
OUR EXPERT
David Bolton has been writing code for Raspberry Pis for over 10 years and now he’s doing it with Rust, both developing and running on his new Raspberry Pi 5.
Previously on coding in Rust… We created a program PokerHand that read in a text file of cards and evaluated each line to figure out the best poker hand. Out of curiosity, we subsequently modified the program so that it no longer used HashMap and HashSet, guessing that maybe those had too much overhead for a small numbers of cards. The HashMap version took 550ns per hand on Ubuntu running in a VM. Without HashMap/HashSet, the time dropped to 125ns, an amazing speed-up of over four times. We put the project files zipped up on GitHub (https://bit.ly/lxf329git). On the Raspberry Pi 5, the time was 175ns per hand.
Measuring the temperature of a Pi
While it’s less important in a Raspberry Pi 3B/4B, the Pi 5 tends to run a bit on the warm side, and if you haven’t got any active cooling, you need to keep an eye on the temperature. You can do this manually from a terminal with this command: $ vcgencmd measure_temp
This outputs something like: temp=48.3’C
Part Five!
Complete your collection. Back issues page 64!
But in a program, it just takes this five-line function that returns an f32, the equivalent of a float in C/C++: fn get_temperature()-> f32 { let mut file = File::open(“/sys/class/thermal/thermal_ zone0/temp”).unwrap();
} let mut contents = String::new(); file.read_to_string(&mut contents).unwrap(); let temp: f32 = contents.trim().parse().unwrap(); temp / 1000.0
Now, if you run that on anything that isn’t a Raspberry Pi, your program will panic. So, before you can call it, check it’s running on a Raspberry Pi with this function, which returns true if it is: fn is_pi_system() -> bool { let info = uname().unwrap(); if info.nodename!=”raspberrypi” { return false;
} if info.machine!=”aarch64”{ return false; } true
}
Before you can compile this, you need to add the uname crate to the project with this: $ cargo add uname This crate is just a wrapper around a call to libc.uname. If you find the uname crate on Crates.io, it includes a link to the GitHub source (https://bit.ly/ lxf329crate), useful if you’re curious to see how it works The function uname() returns a struct with five fields in it. We check two of these: the nodename and the underlying architecture machine. While you might get away with just checking the nodename, if you run it on Raspberry Pi OS running on a virtual machine, the get_temperature() function won’t work.