Skip to main content

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// The secure (`-s`) arms yield to the non-secure (`-ns`) ones when both are
76// enabled, so the only diagnostic in that misconfiguration is the clear
77// `compile_error!` in `crate::nrf`, not a pile of duplicate-import errors.
78#[cfg(any(feature = "nrf9151-ns", feature = "nrf9161-ns"))]
79#[doc(hidden)]
80pub use nrf9120_pac::{self as pac, TIMER0_NS as TIMER0, TIMER1_NS as TIMER1, TIMER2_NS as TIMER2};
81#[cfg(all(
82    any(feature = "nrf9151-s", feature = "nrf9161-s"),
83    not(any(feature = "nrf9151-ns", feature = "nrf9161-ns"))
84))]
85#[doc(hidden)]
86pub use nrf9120_pac::{self as pac, TIMER0_S as TIMER0, TIMER1_S as TIMER1, TIMER2_S as TIMER2};
87#[cfg(feature = "nrf9160-ns")]
88#[doc(hidden)]
89pub use nrf9160_pac::{self as pac, TIMER0_NS as TIMER0, TIMER1_NS as TIMER1, TIMER2_NS as TIMER2};
90#[cfg(all(feature = "nrf9160-s", not(feature = "nrf9160-ns")))]
91#[doc(hidden)]
92pub use nrf9160_pac::{self as pac, TIMER0_S as TIMER0, TIMER1_S as TIMER1, TIMER2_S as TIMER2};
93
94use portable_atomic::{AtomicU32, Ordering};
95use rtic_time::{
96    half_period_counter::calculate_now,
97    timer_queue::{TimerQueue, TimerQueueBackend},
98};
99
100#[doc(hidden)]
101#[macro_export]
102macro_rules! __internal_create_nrf_timer_interrupt {
103    ($mono_backend:ident, $timer:ident) => {
104        #[no_mangle]
105        #[allow(non_snake_case)]
106        unsafe extern "C" fn $timer() {
107            use $crate::TimerQueueBackend;
108            $crate::nrf::timer::$mono_backend::timer_queue().on_monotonic_interrupt();
109        }
110    };
111}
112
113#[doc(hidden)]
114#[macro_export]
115macro_rules! __internal_create_nrf_timer_struct {
116    ($name:ident, $mono_backend:ident, $timer:ident, $tick_rate_hz:expr) => {
117        /// A `Monotonic` based on the nRF Timer peripheral.
118        pub struct $name;
119
120        impl $name {
121            /// Starts the `Monotonic`.
122            ///
123            /// This method must be called only once.
124            pub fn start(timer: $crate::nrf::timer::$timer) {
125                $crate::__internal_create_nrf_timer_interrupt!($mono_backend, $timer);
126
127                const PRESCALER: u8 = match $tick_rate_hz {
128                    16_000_000 => 0,
129                    8_000_000 => 1,
130                    4_000_000 => 2,
131                    2_000_000 => 3,
132                    1_000_000 => 4,
133                    500_000 => 5,
134                    250_000 => 6,
135                    125_000 => 7,
136                    62_500 => 8,
137                    31_250 => 9,
138                    _ => ::core::panic!("Timer cannot run at desired tick rate!"),
139                };
140
141                $crate::nrf::timer::$mono_backend::_start(timer, PRESCALER);
142            }
143        }
144
145        impl $crate::TimerQueueBasedMonotonic for $name {
146            type Backend = $crate::nrf::timer::$mono_backend;
147            type Instant = $crate::fugit::Instant<
148                <Self::Backend as $crate::TimerQueueBackend>::Ticks,
149                1,
150                { $tick_rate_hz },
151            >;
152            type Duration = $crate::fugit::Duration<
153                <Self::Backend as $crate::TimerQueueBackend>::Ticks,
154                1,
155                { $tick_rate_hz },
156            >;
157        }
158
159        $crate::rtic_time::impl_embedded_hal_delay_fugit!($name);
160        $crate::rtic_time::impl_embedded_hal_async_delay_fugit!($name);
161    };
162}
163
164/// Create an Timer0 based monotonic and register the TIMER0 interrupt for it.
165///
166/// See [`crate::nrf::timer`] for more details.
167#[macro_export]
168macro_rules! nrf_timer0_monotonic {
169    ($name:ident, $tick_rate_hz:expr) => {
170        $crate::__internal_create_nrf_timer_struct!($name, Timer0Backend, TIMER0, $tick_rate_hz);
171    };
172}
173
174/// Create an Timer1 based monotonic and register the TIMER1 interrupt for it.
175///
176/// See [`crate::nrf::timer`] for more details.
177#[macro_export]
178macro_rules! nrf_timer1_monotonic {
179    ($name:ident, $tick_rate_hz:expr) => {
180        $crate::__internal_create_nrf_timer_struct!($name, Timer1Backend, TIMER1, $tick_rate_hz);
181    };
182}
183
184/// Create an Timer2 based monotonic and register the TIMER2 interrupt for it.
185///
186/// See [`crate::nrf::timer`] for more details.
187#[macro_export]
188macro_rules! nrf_timer2_monotonic {
189    ($name:ident, $tick_rate_hz:expr) => {
190        $crate::__internal_create_nrf_timer_struct!($name, Timer2Backend, TIMER2, $tick_rate_hz);
191    };
192}
193
194/// Create an Timer3 based monotonic and register the TIMER3 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_timer3_monotonic {
204    ($name:ident, $tick_rate_hz:expr) => {
205        $crate::__internal_create_nrf_timer_struct!($name, Timer3Backend, TIMER3, $tick_rate_hz);
206    };
207}
208
209/// Create an Timer4 based monotonic and register the TIMER4 interrupt for it.
210///
211/// See [`crate::nrf::timer`] for more details.
212#[cfg_attr(
213    docsrs,
214    doc(cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840")))
215)]
216#[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
217#[macro_export]
218macro_rules! nrf_timer4_monotonic {
219    ($name:ident, $tick_rate_hz:expr) => {
220        $crate::__internal_create_nrf_timer_struct!($name, Timer4Backend, TIMER4, $tick_rate_hz);
221    };
222}
223
224macro_rules! make_timer {
225    ($backend_name:ident, $timer:ident, $overflow:ident, $tq:ident$(, doc: ($($doc:tt)*))?) => {
226        /// Timer peripheral based [`TimerQueueBackend`].
227        $(
228            #[cfg_attr(docsrs, doc(cfg($($doc)*)))]
229        )?
230        pub struct $backend_name;
231
232        static $overflow: AtomicU32 = AtomicU32::new(0);
233        static $tq: TimerQueue<$backend_name> = TimerQueue::new();
234
235        impl $backend_name {
236            /// Starts the timer.
237            ///
238            /// **Do not use this function directly.**
239            ///
240            /// Use the prelude macros instead.
241            pub fn _start(timer: $timer, prescaler: u8) {
242                timer.prescaler.write(|w| unsafe { w.prescaler().bits(prescaler) });
243                timer.bitmode.write(|w| w.bitmode()._32bit());
244
245                // Disable interrupts, as preparation
246                timer.intenclr.modify(|_, w| w
247                    .compare0().clear()
248                    .compare1().clear()
249                    .compare2().clear()
250                );
251
252                // Configure compare registers
253                timer.cc[0].write(|w| unsafe { w.cc().bits(0) }); // Dynamic wakeup
254                timer.cc[1].write(|w| unsafe { w.cc().bits(0x0000_0000) }); // Overflow
255                timer.cc[2].write(|w| unsafe { w.cc().bits(0x8000_0000) }); // Half-period
256
257                // Timing critical, make sure we don't get interrupted
258                critical_section::with(|_|{
259                    // Reset the timer
260                    timer.tasks_clear.write(|w| unsafe { w.bits(1) });
261                    timer.tasks_start.write(|w| unsafe { w.bits(1) });
262
263                    // Clear pending events.
264                    // Should be close enough to the timer reset that we don't miss any events.
265                    timer.events_compare[0].write(|w| w);
266                    timer.events_compare[1].write(|w| w);
267                    timer.events_compare[2].write(|w| w);
268
269                    // Make sure overflow counter is synced with the timer value
270                    $overflow.store(0, Ordering::SeqCst);
271
272                    // Initialized the timer queue
273                    $tq.initialize(Self {});
274
275                    // Enable interrupts.
276                    // Should be close enough to the timer reset that we don't miss any events.
277                    timer.intenset.modify(|_, w| w
278                        .compare0().set()
279                        .compare1().set()
280                        .compare2().set()
281                    );
282                });
283
284                // SAFETY: We take full ownership of the peripheral and interrupt vector,
285                // plus we are not using any external shared resources so we won't impact
286                // basepri/source masking based critical sections.
287                unsafe {
288                    crate::set_monotonic_prio(pac::NVIC_PRIO_BITS, pac::Interrupt::$timer);
289                    pac::NVIC::unmask(pac::Interrupt::$timer);
290                }
291            }
292        }
293
294        impl TimerQueueBackend for $backend_name {
295            type Ticks = u64;
296
297            fn now() -> Self::Ticks {
298                let timer = unsafe { &*$timer::PTR };
299
300                calculate_now(
301                    || $overflow.load(Ordering::Relaxed),
302                    || {
303                        timer.tasks_capture[3].write(|w| unsafe { w.bits(1) });
304                        timer.cc[3].read().bits()
305                    }
306                )
307            }
308
309            fn on_interrupt() {
310                let timer = unsafe { &*$timer::PTR };
311
312                // If there is a compare match on channel 1, it is an overflow
313                if timer.events_compare[1].read().bits() & 1 != 0 {
314                    timer.events_compare[1].write(|w| w);
315                    let prev = $overflow.fetch_add(1, Ordering::Relaxed);
316                    ::core::assert!(prev % 2 == 1, "Monotonic must have skipped an interrupt!");
317                }
318
319                // If there is a compare match on channel 2, it is a half-period overflow
320                if timer.events_compare[2].read().bits() & 1 != 0 {
321                    timer.events_compare[2].write(|w| w);
322                    let prev = $overflow.fetch_add(1, Ordering::Relaxed);
323                    ::core::assert!(prev % 2 == 0, "Monotonic must have skipped an interrupt!");
324                }
325            }
326
327            fn set_compare(instant: Self::Ticks) {
328                let timer = unsafe { &*$timer::PTR };
329                timer.cc[0].write(|w| unsafe { w.cc().bits(instant as u32) });
330            }
331
332            fn clear_compare_flag() {
333                let timer = unsafe { &*$timer::PTR };
334                timer.events_compare[0].write(|w| w);
335            }
336
337            fn pend_interrupt() {
338                pac::NVIC::pend(pac::Interrupt::$timer);
339            }
340
341            fn timer_queue() -> &'static TimerQueue<$backend_name> {
342                &$tq
343            }
344        }
345    };
346}
347
348make_timer!(Timer0Backend, TIMER0, TIMER0_OVERFLOWS, TIMER0_TQ);
349make_timer!(Timer1Backend, TIMER1, TIMER1_OVERFLOWS, TIMER1_TQ);
350make_timer!(Timer2Backend, TIMER2, TIMER2_OVERFLOWS, TIMER2_TQ);
351#[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
352make_timer!(Timer3Backend, TIMER3, TIMER3_OVERFLOWS, TIMER3_TQ, doc: (any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840")));
353#[cfg(any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840"))]
354make_timer!(Timer4Backend, TIMER4, TIMER4_OVERFLOWS, TIMER4_TQ, doc: (any(feature = "nrf52832", feature = "nrf52833", feature = "nrf52840")));