Hello ,
I want to share a mutable reference to cortex_m::peripheral::itm::Stim
across multiple functions, and I'm not sure what is the ergonomic way to do so in Rust.
Most examples on using ITM
looks similar to the program below, which takes ownership of the peripherals in fn main()
and using them inside fn main()
.
#![no_main]
#![no_std]
use panic_itm as _;
use stm32f1xx_hal as _;
use cortex_m::{iprintln, Peripherals};
use cortex_m_rt::entry;
#[entry]
fn main() -> ! {
let mut p = Peripherals::take().unwrap();
let stim = &mut p.ITM.stim[0];
iprintln!(stim, "Hello, world!");
loop {}
}
I want to call iprintln!()
from multiple functions, but unlike println!()
it also takes a reference to
cortex_m::peripheral::itm::Stim
as a parameter.
I initially had two options to emerge in mind, and both don't seem to be good solutions.
-
passing a reference to
Stim
every time
This option seems undesirable, since it incurs overhead of passing an extra parameter every time functionfoo()
is called (Let's assume that the function being called is long to be inlined). -
Sharing
Stim
globally by definingstim
asstatic mut
?
I think this option will make the program look very ugly and it just doesn't feel right..
I assume thePeripherals::take()
API intends to prevent data races to peripherals,
and simply using astatic mut
just feels awkward.
Is there an ergonomic way to share Stim
across multiple functions, or should I go with Option 2??
I'd really appreciate any advice! Thank you for reading along
// Example of passing `Stim` as parameter every time (Option 1)
#![no_main]
#![no_std]
use panic_itm as _;
use stm32f1xx_hal as _;
use cortex_m::peripheral::itm::Stim
use cortex_m::{iprintln, Peripherals};
use cortex_m_rt::entry;
fn foo(stim: &mut Stim) {
iprintln!(stim, "HELLO WORLD");
// Imagine very lo~~~ng code exists here
// that makes it undesirable to inline this function
}
#[entry]
fn main() -> ! {
let mut p = Peripherals::take().unwrap();
let stim = &mut p.ITM.stim[0];
iprintln!(stim, "Hello, world!");
for _ in 10000 {
foo(stim);
}
loop {}
}