rp2040_monotonic/
lib.rs

1//! # [`Monotonic`] implementation based on RP2040's `Timer` peripheral.
2//!
3//! Uses [`fugit`] as underlying time library.
4//!
5//! [`fugit`]: https://docs.rs/crate/fugit
6//! [`Monotonic`]: https://docs.rs/rtic-monotonic
7
8#![no_std]
9
10pub use fugit::{self, ExtU64};
11use rp2040_pac::{RESETS, TIMER};
12use rtic_monotonic::Monotonic;
13
14/// RP2040 `Timer` implementation for `rtic_monotonic::Monotonic`.
15pub struct Rp2040Monotonic {
16    timer: TIMER,
17}
18
19impl Rp2040Monotonic {
20    /// Create a new `Monotonic` based on RP2040's `Timer` peripheral.
21    pub fn new(timer: TIMER) -> Self {
22        Self { timer }
23    }
24}
25
26impl Monotonic for Rp2040Monotonic {
27    const DISABLE_INTERRUPT_ON_EMPTY_QUEUE: bool = false;
28
29    type Instant = fugit::TimerInstantU64<1_000_000>;
30    type Duration = fugit::TimerDurationU64<1_000_000>;
31
32    fn now(&mut self) -> Self::Instant {
33        let mut hi0 = self.timer.timerawh.read().bits();
34        loop {
35            let low = self.timer.timerawl.read().bits();
36            let hi1 = self.timer.timerawh.read().bits();
37            if hi0 == hi1 {
38                break Self::Instant::from_ticks((u64::from(hi0) << 32) | u64::from(low));
39            }
40            hi0 = hi1;
41        }
42    }
43
44    unsafe fn reset(&mut self) {
45        let resets = &*RESETS::ptr();
46        resets.reset.modify(|_, w| w.timer().clear_bit());
47        while resets.reset_done.read().timer().bit_is_clear() {}
48        self.timer.inte.modify(|_, w| w.alarm_0().set_bit());
49    }
50
51    fn set_compare(&mut self, instant: Self::Instant) {
52        let now = self.now();
53
54        let max = u32::MAX as u64;
55
56        // Since the timer may or may not overflow based on the requested compare val, we check
57        // how many ticks are left.
58        let val = match instant.checked_duration_since(now) {
59            Some(x) if x.ticks() <= max => instant.duration_since_epoch().ticks() & max, // Will not overflow
60            _ => 0, // Will overflow or in the past, set the same value as after overflow to not get extra interrupts
61        };
62
63        self.timer.alarm0.write(|w| unsafe { w.bits(val as u32) });
64    }
65
66    fn clear_compare_flag(&mut self) {
67        self.timer.intr.modify(|_, w| w.alarm_0().bit(true));
68    }
69
70    fn zero() -> Self::Instant {
71        Self::Instant::from_ticks(0)
72    }
73}