|
| 1 | +use fugit::{ExtU32, MicrosDurationU32}; |
| 2 | +use stm32h5xx_hal::stm32; |
| 3 | + |
| 4 | +#[non_exhaustive] |
| 5 | +pub struct Timer<const CYCLES_PER_US: u32>; |
| 6 | + |
| 7 | +impl<const CYCLES_PER_US: u32> Timer<CYCLES_PER_US> { |
| 8 | + #[allow(dead_code)] |
| 9 | + pub fn enable_timer(cp: &mut stm32::CorePeripherals) -> Self { |
| 10 | + cp.DCB.enable_trace(); |
| 11 | + cp.DWT.enable_cycle_counter(); |
| 12 | + |
| 13 | + Timer |
| 14 | + } |
| 15 | + |
| 16 | + /// Returns duration since timer start |
| 17 | + pub fn now(&self) -> MicrosDurationU32 { |
| 18 | + (stm32::DWT::cycle_count() / CYCLES_PER_US).micros() |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +#[allow(dead_code)] |
| 23 | +pub fn is_pax_low(pin: u8) -> bool { |
| 24 | + let gpioa = unsafe { &*stm32::GPIOA::PTR }; |
| 25 | + gpioa.idr().read().id(pin).is_low() |
| 26 | +} |
| 27 | + |
| 28 | +#[allow(dead_code)] |
| 29 | +#[derive(Debug, defmt::Format)] |
| 30 | +pub struct ErrorTimedOut; |
| 31 | + |
| 32 | +#[allow(dead_code)] |
| 33 | +pub fn await_lo<const CYCLES_PER_US: u32>( |
| 34 | + timer: &Timer<CYCLES_PER_US>, |
| 35 | + pin: u8, |
| 36 | + timeout: MicrosDurationU32, |
| 37 | +) -> Result<MicrosDurationU32, ErrorTimedOut> { |
| 38 | + await_p(timer, || is_pax_low(pin), timeout) |
| 39 | +} |
| 40 | + |
| 41 | +#[allow(dead_code)] |
| 42 | +pub fn await_hi<const CYCLES_PER_US: u32>( |
| 43 | + timer: &Timer<CYCLES_PER_US>, |
| 44 | + pin: u8, |
| 45 | + timeout: MicrosDurationU32, |
| 46 | +) -> Result<MicrosDurationU32, ErrorTimedOut> { |
| 47 | + await_p(timer, || !is_pax_low(pin), timeout) |
| 48 | +} |
| 49 | + |
| 50 | +#[allow(dead_code)] |
| 51 | +pub fn await_p<const CYCLES_PER_US: u32>( |
| 52 | + timer: &Timer<CYCLES_PER_US>, |
| 53 | + mut p: impl FnMut() -> bool, |
| 54 | + timeout: MicrosDurationU32, |
| 55 | +) -> Result<MicrosDurationU32, ErrorTimedOut> { |
| 56 | + let before = timer.now(); |
| 57 | + |
| 58 | + loop { |
| 59 | + let passed_time = timer.now() - before; |
| 60 | + if p() { |
| 61 | + return Ok(passed_time); |
| 62 | + } |
| 63 | + if passed_time > timeout { |
| 64 | + return Err(ErrorTimedOut); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments