Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How can I properly modify a global variable from an interrupt service routine?
I am using the avr-hal crate to write firmware for an atmega328p. I'm trying to modify a register value from an interrupt service routine, but I'm having issues with borrowing when trying to do so that I'm not really sure how to properly solve. I've read that mutex's are probably a way to do this, and avr-hal does provide them with avr_device::interrupt::mutex
, but I'm not exactly sure how to go about that, or if there's a better method. In general, I'm not familiar with how interrupts should be handled in rust. For example:
#![no_std]
#![no_main]
#![feature(abi_avr_interrupt)]
use atmega_hal as hal;
use panic_halt as _;
#[hal::entry]
fn main() -> {
let peripherals = hal::Peripherals::take().unwrap();
let pins = hal::pins!(peripherals)
let mut test_pin = pins.pb0.into_output();
let mut test_output = pins.pc3.into_pull_up_input();
peripherals.EXINT.pcicr.modify(|_, w| w.pcie().bits(1 << 2));
peripherals.EXINT.pcmsk1.modify(|_, w| w.pcint().bits(1 << 3));
unsafe { avr_device::interrupt::enable(); }
loop {
test_pin.toggle();
}
}
#[avr_device::interrupt(atmega328p)]
fn PCINT1() {
// I want to use peripherals here to be able to modify registers. For example, something like
// peripherals.TC1.ocr1a.write(|w| w.bits(1000))
}
I thought adding something in the global scope like
static GLOBAL_PERIPHERALS: avr_device::interrupt::Mutex<RefCell<Option<hal::Peripherals>>> = avr_device::interrupt::Mutex::new(RefCell::new(None));
And then modifying things in the critical sections with something like:
avr_device::interrupt::free(|cs| {
let local_peripherals = GLOBAL_PERIPHERALS.borrow(cs).borrow()
});
but I'm really not sure how or where to properly do that. Or if there's other ways, or better ways to handle interrupts.
1 post - 1 participant
🏷️ Rust_feed