Skip to content

Instantly share code, notes, and snippets.

@SamP20
Last active May 4, 2019 18:17
Show Gist options
  • Save SamP20/f287361d4105131c899be9d0dbd7bd4f to your computer and use it in GitHub Desktop.
Save SamP20/f287361d4105131c899be9d0dbd7bd4f to your computer and use it in GitHub Desktop.
Example interrupt API
[entry]
fn main() -> ! {
let p = cortex_m::Peripherals::take().unwrap();
let interrupts = Interrupts::new(p.NVIC);
let a: u32 = 5;
let b: u32 = 6;
let c: u32 = 7;
let uarte = interrupts.USART0.enable(&mut || {
let a2 = a; // Copy type
let b2 = &b; // Immutable reference
let c2 = &mut c; //Mutable reference
});
//uarte now contains a mutable reference to the closure
// some time later...
let uartd = uarte.disable(); // Consumes uarte
}
////////////////////
// Implementation
///////////////////
use std::mem::{MaybeUninit, transmute};
use std::marker::PhantomData;
static mut USART0_HANDLER: MaybeUninit<&'static mut dyn FnMut()> = MaybeUninit::uninit();
struct DisabledUSART0;
impl DisabledUSART0 {
fn enable<'a>(self, cb: &'a mut dyn FnMut()) -> EnabledUSART0<'a> {
USART0_HANDLER.write(transmute::<&'a mut dyn FnMut(), &'static mut dyn FnMut()>(cb));
// Enable USART0 in the NVIC
EnabledUSART0 {
_marker: PhantomData
}
}
}
struct EnabledUSART0<'a> {
_marker: std::marker::PhantomData<&'a mut dyn FnMut>
}
impl<'a> EnabledUSART0<'a> {
fn disable(self) -> DisabledUSART0 {
// Disable USART0 in the NVIC
DisabledUSART0
}
}
#[no_mangle]
fn USART0() {
unsafe { &mut *USART0_HANDLER.as_mut_ptr() }();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment