rtic_monotonics/nrf/
timer.rs

1//! [`Monotonic`](rtic_time::Monotonic) implementation for the 32-bit timers of the nRF series.
2//!
3//! Not all timers are available on all parts. Ensure that only the available
4//! timers are exposed by having the correct `nrf52*` feature enabled for `rtic-monotonics`.
5//!
6//! # Example
7//!
8//! ```
9//! use rtic_monotonics::nrf::timer::prelude::*;
10//! nrf_timer0_monotonic!(Mono);
11//!
12//! fn init() {
13//!     # // This is normally provided by the selected PAC
14//!     # let timer = unsafe { core::mem::transmute(()) };
15//!     // Start the monotonic
16//!     Mono::start(timer);
17//! }
18//!
19//! async fn usage() {
20//!     loop {
21//!          // Use the monotonic
22//!          let timestamp = Mono::now();
23//!          Mono::delay(100.millis()).await;
24//!     }
25//! }
26//! ```
27
28/// Common definitions and traits for using the nRF Timer monotonics
29pub mod prelude {
30    pub use crate::nrf_timer0_monotonic;
31    pub use crate::nrf_timer1_monotonic;
32    pub use crate::nrf_timer2_monotonic;
33    #[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
34    pub use crate::nrf_timer3_monotonic;
35    #[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
36    pub use crate::nrf_timer4_monotonic;
37
38    pub use crate::Monotonic;
39    pub use fugit::{self, ExtU64, ExtU64Ceil};
40}
41
42#[cfg(feature = "nrf52805")]
43#[doc(hidden)]
44pub use nrf52805_pac::{self as pac, TIMER0, TIMER1, TIMER2};
45#[cfg(feature = "nrf52810")]
46#[doc(hidden)]
47pub use nrf52810_pac::{self as pac, TIMER0, TIMER1, TIMER2};
48#[cfg(feature = "nrf52811")]
49#[doc(hidden)]
50pub use nrf52811_pac::{self as pac, TIMER0, TIMER1, TIMER2};
51#[cfg(feature = "nrf52832")]
52#[doc(hidden)]
53pub use nrf52832_pac::{self as pac, TIMER0, TIMER1, TIMER2, TIMER3, TIMER4};
54#[cfg(feature = "nrf52833")]
55#[doc(hidden)]
56pub use nrf52833_pac::{self as pac, TIMER0, TIMER1, TIMER2, TIMER3, TIMER4};
57#[cfg(feature = "nrf52840")]
58#[doc(hidden)]
59pub use nrf52840_pac::{self as pac, TIMER0, TIMER1, TIMER2, TIMER3, TIMER4};
60#[cfg(feature = "nrf5340-app")]
61#[doc(hidden)]
62pub use nrf5340_app_pac::{
63    self as pac, TIMER0_NS as TIMER0, TIMER1_NS as TIMER1, TIMER2_NS as TIMER2,
64};
65#[cfg(feature = "nrf5340-net")]
66#[doc(hidden)]
67pub use nrf5340_net_pac::{
68    self as pac, TIMER0_NS as TIMER0, TIMER1_NS as TIMER1, TIMER2_NS as TIMER2,
69};
70#[cfg(feature = "nrf9160")]
71#[doc(hidden)]
72pub use nrf9160_pac::{self as pac, TIMER0_NS as TIMER0, TIMER1_NS as TIMER1, TIMER2_NS as TIMER2};
73
74use portable_atomic::{AtomicU32, Ordering};
75use rtic_time::{
76    half_period_counter::calculate_now,
77    timer_queue::{TimerQueue, TimerQueueBackend},
78};
79
80#[doc(hidden)]
81#[macro_export]
82macro_rules! __internal_create_nrf_timer_interrupt {
83    ($mono_backend:ident, $timer:ident) => {
84        #[no_mangle]
85        #[allow(non_snake_case)]
86        unsafe extern "C" fn $timer() {
87            use $crate::TimerQueueBackend;
88            $crate::nrf::timer::$mono_backend::timer_queue().on_monotonic_interrupt();
89        }
90    };
91}
92
93#[doc(hidden)]
94#[macro_export]
95macro_rules! __internal_create_nrf_timer_struct {
96    ($name:ident, $mono_backend:ident, $timer:ident, $tick_rate_hz:expr) => {
97        /// A `Monotonic` based on the nRF Timer peripheral.
98        pub struct $name;
99
100        impl $name {
101            /// Starts the `Monotonic`.
102            ///
103            /// This method must be called only once.
104            pub fn start(timer: $crate::nrf::timer::$timer) {
105                $crate::__internal_create_nrf_timer_interrupt!($mono_backend, $timer);
106
107                const PRESCALER: u8 = match $tick_rate_hz {
108                    16_000_000 => 0,
109                    8_000_000 => 1,
110                    4_000_000 => 2,
111                    2_000_000 => 3,
112                    1_000_000 => 4,
113                    500_000 => 5,
114                    250_000 => 6,
115                    125_000 => 7,
116                    62_500 => 8,
117                    31_250 => 9,
118                    _ => panic!("Timer cannot run at desired tick rate!"),
119                };
120
121                $crate::nrf::timer::$mono_backend::_start(timer, PRESCALER);
122            }
123        }
124
125        impl $crate::TimerQueueBasedMonotonic for $name {
126            type Backend = $crate::nrf::timer::$mono_backend;
127            type Instant = $crate::fugit::Instant<
128                <Self::Backend as $crate::TimerQueueBackend>::Ticks,
129                1,
130                { $tick_rate_hz },
131            >;
132            type Duration = $crate::fugit::Duration<
133                <Self::Backend as $crate::TimerQueueBackend>::Ticks,
134                1,
135                { $tick_rate_hz },
136            >;
137        }
138
139        $crate::rtic_time::impl_embedded_hal_delay_fugit!($name);
140        $crate::rtic_time::impl_embedded_hal_async_delay_fugit!($name);
141    };
142}
143
144/// Create an Timer0 based monotonic and register the TIMER0 interrupt for it.
145///
146/// See [`crate::nrf::timer`] for more details.
147#[macro_export]
148macro_rules! nrf_timer0_monotonic {
149    ($name:ident, $tick_rate_hz:expr) => {
150        $crate::__internal_create_nrf_timer_struct!($name, Timer0Backend, TIMER0, $tick_rate_hz);
151    };
152}
153
154/// Create an Timer1 based monotonic and register the TIMER1 interrupt for it.
155///
156/// See [`crate::nrf::timer`] for more details.
157#[macro_export]
158macro_rules! nrf_timer1_monotonic {
159    ($name:ident, $tick_rate_hz:expr) => {
160        $crate::__internal_create_nrf_timer_struct!($name, Timer1Backend, TIMER1, $tick_rate_hz);
161    };
162}
163
164/// Create an Timer2 based monotonic and register the TIMER2 interrupt for it.
165///
166/// See [`crate::nrf::timer`] for more details.
167#[macro_export]
168macro_rules! nrf_timer2_monotonic {
169    ($name:ident, $tick_rate_hz:expr) => {
170        $crate::__internal_create_nrf_timer_struct!($name, Timer2Backend, TIMER2, $tick_rate_hz);
171    };
172}
173
174/// Create an Timer3 based monotonic and register the TIMER3 interrupt for it.
175///
176/// See [`crate::nrf::timer`] for more details.
177#[cfg_attr(
178    docsrs,
179    doc(cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840")))
180)]
181#[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
182#[macro_export]
183macro_rules! nrf_timer3_monotonic {
184    ($name:ident, $tick_rate_hz:expr) => {
185        $crate::__internal_create_nrf_timer_struct!($name, Timer3Backend, TIMER3, $tick_rate_hz);
186    };
187}
188
189/// Create an Timer4 based monotonic and register the TIMER4 interrupt for it.
190///
191/// See [`crate::nrf::timer`] for more details.
192#[cfg_attr(
193    docsrs,
194    doc(cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840")))
195)]
196#[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
197#[macro_export]
198macro_rules! nrf_timer4_monotonic {
199    ($name:ident, $tick_rate_hz:expr) => {
200        $crate::__internal_create_nrf_timer_struct!($name, Timer4Backend, TIMER4, $tick_rate_hz);
201    };
202}
203
204macro_rules! make_timer {
205    ($backend_name:ident, $timer:ident, $overflow:ident, $tq:ident$(, doc: ($($doc:tt)*))?) => {
206        /// Timer peripheral based [`TimerQueueBackend`].
207        $(
208            #[cfg_attr(docsrs, doc(cfg($($doc)*)))]
209        )?
210        pub struct $backend_name;
211
212        static $overflow: AtomicU32 = AtomicU32::new(0);
213        static $tq: TimerQueue<$backend_name> = TimerQueue::new();
214
215        impl $backend_name {
216            /// Starts the timer.
217            ///
218            /// **Do not use this function directly.**
219            ///
220            /// Use the prelude macros instead.
221            pub fn _start(timer: $timer, prescaler: u8) {
222                timer.prescaler.write(|w| unsafe { w.prescaler().bits(prescaler) });
223                timer.bitmode.write(|w| w.bitmode()._32bit());
224
225                // Disable interrupts, as preparation
226                timer.intenclr.modify(|_, w| w
227                    .compare0().clear()
228                    .compare1().clear()
229                    .compare2().clear()
230                );
231
232                // Configure compare registers
233                timer.cc[0].write(|w| unsafe { w.cc().bits(0) }); // Dynamic wakeup
234                timer.cc[1].write(|w| unsafe { w.cc().bits(0x0000_0000) }); // Overflow
235                timer.cc[2].write(|w| unsafe { w.cc().bits(0x8000_0000) }); // Half-period
236
237                // Timing critical, make sure we don't get interrupted
238                critical_section::with(|_|{
239                    // Reset the timer
240                    timer.tasks_clear.write(|w| unsafe { w.bits(1) });
241                    timer.tasks_start.write(|w| unsafe { w.bits(1) });
242
243                    // Clear pending events.
244                    // Should be close enough to the timer reset that we don't miss any events.
245                    timer.events_compare[0].write(|w| w);
246                    timer.events_compare[1].write(|w| w);
247                    timer.events_compare[2].write(|w| w);
248
249                    // Make sure overflow counter is synced with the timer value
250                    $overflow.store(0, Ordering::SeqCst);
251
252                    // Initialized the timer queue
253                    $tq.initialize(Self {});
254
255                    // Enable interrupts.
256                    // Should be close enough to the timer reset that we don't miss any events.
257                    timer.intenset.modify(|_, w| w
258                        .compare0().set()
259                        .compare1().set()
260                        .compare2().set()
261                    );
262                });
263
264                // SAFETY: We take full ownership of the peripheral and interrupt vector,
265                // plus we are not using any external shared resources so we won't impact
266                // basepri/source masking based critical sections.
267                unsafe {
268                    crate::set_monotonic_prio(pac::NVIC_PRIO_BITS, pac::Interrupt::$timer);
269                    pac::NVIC::unmask(pac::Interrupt::$timer);
270                }
271            }
272        }
273
274        impl TimerQueueBackend for $backend_name {
275            type Ticks = u64;
276
277            fn now() -> Self::Ticks {
278                let timer = unsafe { &*$timer::PTR };
279
280                calculate_now(
281                    || $overflow.load(Ordering::Relaxed),
282                    || {
283                        timer.tasks_capture[3].write(|w| unsafe { w.bits(1) });
284                        timer.cc[3].read().bits()
285                    }
286                )
287            }
288
289            fn on_interrupt() {
290                let timer = unsafe { &*$timer::PTR };
291
292                // If there is a compare match on channel 1, it is an overflow
293                if timer.events_compare[1].read().bits() & 1 != 0 {
294                    timer.events_compare[1].write(|w| w);
295                    let prev = $overflow.fetch_add(1, Ordering::Relaxed);
296                    assert!(prev % 2 == 1, "Monotonic must have skipped an interrupt!");
297                }
298
299                // If there is a compare match on channel 2, it is a half-period overflow
300                if timer.events_compare[2].read().bits() & 1 != 0 {
301                    timer.events_compare[2].write(|w| w);
302                    let prev = $overflow.fetch_add(1, Ordering::Relaxed);
303                    assert!(prev % 2 == 0, "Monotonic must have skipped an interrupt!");
304                }
305            }
306
307            fn set_compare(instant: Self::Ticks) {
308                let timer = unsafe { &*$timer::PTR };
309                timer.cc[0].write(|w| unsafe { w.cc().bits(instant as u32) });
310            }
311
312            fn clear_compare_flag() {
313                let timer = unsafe { &*$timer::PTR };
314                timer.events_compare[0].write(|w| w);
315            }
316
317            fn pend_interrupt() {
318                pac::NVIC::pend(pac::Interrupt::$timer);
319            }
320
321            fn timer_queue() -> &'static TimerQueue<$backend_name> {
322                &$tq
323            }
324        }
325    };
326}
327
328make_timer!(Timer0Backend, TIMER0, TIMER0_OVERFLOWS, TIMER0_TQ);
329make_timer!(Timer1Backend, TIMER1, TIMER1_OVERFLOWS, TIMER1_TQ);
330make_timer!(Timer2Backend, TIMER2, TIMER2_OVERFLOWS, TIMER2_TQ);
331#[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
332make_timer!(Timer3Backend, TIMER3, TIMER3_OVERFLOWS, TIMER3_TQ, doc: (any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840")));
333#[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
334make_timer!(Timer4Backend, TIMER4, TIMER4_OVERFLOWS, TIMER4_TQ, doc: (any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840")));