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