1#![no_std]
9
10pub use fugit::{self, ExtU64};
11
12use rp2040_hal::pac::{RESETS, TIMER};
13use rtic_monotonic::Monotonic;
14
15pub struct Rp2040Monotonic {
17 timer: TIMER,
18}
19
20impl Rp2040Monotonic {
21 pub fn new(timer: TIMER) -> Self {
23 Self { timer }
24 }
25}
26
27impl Monotonic for Rp2040Monotonic {
28 const DISABLE_INTERRUPT_ON_EMPTY_QUEUE: bool = false;
29
30 type Instant = fugit::TimerInstantU64<1_000_000>;
31 type Duration = fugit::TimerDurationU64<1_000_000>;
32
33 fn now(&mut self) -> Self::Instant {
34 let mut hi0 = self.timer.timerawh().read().bits();
35 loop {
36 let low = self.timer.timerawl().read().bits();
37 let hi1 = self.timer.timerawh().read().bits();
38 if hi0 == hi1 {
39 break Self::Instant::from_ticks((u64::from(hi0) << 32) | u64::from(low));
40 }
41 hi0 = hi1;
42 }
43 }
44
45 unsafe fn reset(&mut self) {
46 let resets = &*RESETS::ptr();
47 resets.reset().modify(|_, w| w.timer().clear_bit());
48 while resets.reset_done().read().timer().bit_is_clear() {}
49 self.timer.inte().modify(|_, w| w.alarm_0().set_bit());
50 }
51
52 fn set_compare(&mut self, instant: Self::Instant) {
53 let now = self.now();
54
55 let max = u32::MAX as u64;
56
57 let val = match instant.checked_duration_since(now) {
60 Some(x) if x.ticks() <= max => instant.duration_since_epoch().ticks() & max, _ => 0, };
63
64 self.timer.alarm0().write(|w| unsafe { w.bits(val as u32) });
65 }
66
67 fn clear_compare_flag(&mut self) {
68 self.timer.intr().modify(|_, w| w.alarm_0().bit(true));
69 }
70
71 fn zero() -> Self::Instant {
72 Self::Instant::from_ticks(0)
73 }
74}