Skip to main content

rtic_rp_monotonic/
lib.rs

1//! # [`Monotonic`] implementation based on RP2040's `Timer` peripheral.
2//! fork by https://github.com/korken89/rp2040-monotonic
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};
11
12use rp2040_hal::pac::{RESETS, TIMER};
13use rtic_monotonic::Monotonic;
14
15/// RP2040 `Timer` implementation for `rtic_monotonic::Monotonic`.
16pub struct Rp2040Monotonic {
17    timer: TIMER,
18}
19
20impl Rp2040Monotonic {
21    /// Create a new `Monotonic` based on RP2040's `Timer` peripheral.
22    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        // Since the timer may or may not overflow based on the requested compare val, we check
58        // how many ticks are left.
59        let val = match instant.checked_duration_since(now) {
60            Some(x) if x.ticks() <= max => instant.duration_since_epoch().ticks() & max, // Will not overflow
61            _ => 0, // Will overflow or in the past, set the same value as after overflow to not get extra interrupts
62        };
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}