I am an embedded C developer that recently started learning Rust. To help learn, I am beginning to develop a fairly large application in Rust for a Nordic nRf52832 MCU. I am using the nrf52832_pac crate for the project.
I was looking for some better direction or a recommended way to set this as a project global variable instead of passing it through each function in the project. It will function by passing the object around but it feels cluttered and sloppy.
My initial thought was to declare the global variable to be of type Option<Peripherals>
initialized to None
. Doing this will satisfy the compiler until the global variable is attempted to be assigned.
static mut _PERIPHERALS: Option<nrf52832_pac::Peripherals> = None;
pub fn init(){
unsafe {_PERIPHERALS = Some(nrf52832_pac::Peripherals::take().unwrap()); }
}
pub fn set_pin_state(pin: u8, state: PinState) {
unsafe {
let p = _PERIPHERALS.unwrap();
match state{
PinState::PinLow => p.P0.outclr.write(|w| w.bits(1 << pin)),
PinState::PinHigh => p.P0.outset.write(|w| w.bits(1 << pin)),
_ => ()
};
};
}
This gives the following error at _PERIPHERALS.unwrap()
:
error[E0507]: cannot move out of static item `PERIPHERALS`
--> src/mcu.rs:80:17
|
80 | let p = PERIPHERALS.unwrap();
| ^^^^^^^^^^^ move occurs because `PERIPHERALS` has type `core::option::Option<nrf52832_pac::Peripherals>`, which does not implement the `Copy` trait
I have begun to derive the Copy
trait but I don't feel like this is the right path. There must be a better way for a global peripherals object that I am not familiar with using.