Last active
May 4, 2019 18:17
-
-
Save SamP20/f287361d4105131c899be9d0dbd7bd4f to your computer and use it in GitHub Desktop.
Example interrupt API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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