rtic-monotonics 2.2.1

A library that provides implementations of the Monotonic trait from rtic-time
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! [`Monotonic`](rtic_time::Monotonic) implementations for STM32 chips.
//!
//! Not all timers are available on all parts. Ensure that only available
//! timers are exposed by having the correct `stm32*` feature enabled for `rtic-monotonics`.
//!
//! # Example
//!
//! ```
//! use rtic_monotonics::stm32::prelude::*;
//!
//! // Create the type `Mono`. It will manage the TIM2 timer, and
//! // run with a resolution of 1 µs (1,000,000 ticks per second).
//! stm32_tim2_monotonic!(Mono, 1_000_000);
//!
//! fn init() {
//!     // If using `embassy-stm32` HAL, timer clock can be read out like this:
//!     let timer_clock_hz = embassy_stm32::peripherals::TIM2::frequency();
//!     // Or define it manually if you are using another HAL or know the
//!     // correct frequency:
//!     let timer_clock_hz = 64_000_000;
//!
//!     // Start the monotonic. The TIM2 prescaler is calculated from the
//!     // clock frequency given here, and the resolution given to the
//!     // `stm32_tim2_monotonic!` macro call above. No PAC object is required.
//!     Mono::start(timer_clock_hz);
//! }
//!
//! async fn usage() {
//!     loop {
//!          // You can use the monotonic to get the time...
//!          let timestamp = Mono::now();
//!          // ...and you can use it to add a delay to this async function
//!          Mono::delay(100.millis()).await;
//!     }
//! }
//! ```

/// Common definitions and traits for using the STM32 monotonics
pub mod prelude {
    #[cfg(feature = "stm32_tim2")]
    pub use crate::stm32_tim2_monotonic;

    #[cfg(feature = "stm32_tim3")]
    pub use crate::stm32_tim3_monotonic;

    #[cfg(feature = "stm32_tim4")]
    pub use crate::stm32_tim4_monotonic;

    #[cfg(feature = "stm32_tim5")]
    pub use crate::stm32_tim5_monotonic;

    #[cfg(feature = "stm32_tim15")]
    pub use crate::stm32_tim15_monotonic;

    pub use crate::Monotonic;
    pub use fugit::{self, ExtU64, ExtU64Ceil};
}

use portable_atomic::{AtomicU64, Ordering};
use rtic_time::{
    half_period_counter::calculate_now,
    timer_queue::{TimerQueue, TimerQueueBackend},
};
use stm32_metapac as pac;

mod _generated {
    #![allow(dead_code)]
    #![allow(unused_imports)]
    #![allow(non_snake_case)]

    include!(concat!(env!("OUT_DIR"), "/_generated.rs"));
}

#[doc(hidden)]
#[macro_export]
macro_rules! __internal_create_stm32_timer_interrupt {
    ($mono_backend:ident, $interrupt_name:ident) => {
        #[no_mangle]
        #[allow(non_snake_case)]
        unsafe extern "C" fn $interrupt_name() {
            use $crate::TimerQueueBackend;
            $crate::stm32::$mono_backend::timer_queue().on_monotonic_interrupt();
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __internal_create_stm32_timer_struct {
    ($name:ident, $mono_backend:ident, $timer:ident, $tick_rate_hz:expr) => {
        /// A `Monotonic` based on an STM32 timer peripheral.
        pub struct $name;

        impl $name {
            /// Starts the `Monotonic`.
            ///
            /// - `tim_clock_hz`: `TIMx` peripheral clock frequency.
            ///
            /// Panics if it is impossible to achieve the desired monotonic tick rate based
            /// on the given `tim_clock_hz` parameter. If that happens, adjust the desired monotonic tick rate.
            ///
            /// This method must be called only once.
            pub fn start(tim_clock_hz: u32) {
                $crate::__internal_create_stm32_timer_interrupt!($mono_backend, $timer);

                $crate::stm32::$mono_backend::_start(tim_clock_hz, $tick_rate_hz);
            }
        }

        impl $crate::TimerQueueBasedMonotonic for $name {
            type Backend = $crate::stm32::$mono_backend;
            type Instant = $crate::fugit::Instant<
                <Self::Backend as $crate::TimerQueueBackend>::Ticks,
                1,
                { $tick_rate_hz },
            >;
            type Duration = $crate::fugit::Duration<
                <Self::Backend as $crate::TimerQueueBackend>::Ticks,
                1,
                { $tick_rate_hz },
            >;
        }

        $crate::rtic_time::impl_embedded_hal_delay_fugit!($name);
        $crate::rtic_time::impl_embedded_hal_async_delay_fugit!($name);
    };
}

/// Create a TIM2 based monotonic and register the TIM2 interrupt for it.
///
/// See [`crate::stm32`] for more details.
///
/// # Arguments
///
/// * `name` - The name that the monotonic type will have.
/// * `tick_rate_hz` - The tick rate of the timer peripheral.
///
#[cfg(feature = "stm32_tim2")]
#[macro_export]
macro_rules! stm32_tim2_monotonic {
    ($name:ident, $tick_rate_hz:expr) => {
        $crate::__internal_create_stm32_timer_struct!($name, Tim2Backend, TIM2, $tick_rate_hz);
    };
}

/// Create a TIM3 based monotonic and register the TIM3 interrupt for it.
///
/// See [`crate::stm32`] for more details.
///
/// # Arguments
///
/// * `name` - The name that the monotonic type will have.
/// * `tick_rate_hz` - The tick rate of the timer peripheral.
///
#[cfg(feature = "stm32_tim3")]
#[macro_export]
macro_rules! stm32_tim3_monotonic {
    ($name:ident, $tick_rate_hz:expr) => {
        $crate::__internal_create_stm32_timer_struct!($name, Tim3Backend, TIM3, $tick_rate_hz);
    };
}

/// Create a TIM4 based monotonic and register the TIM4 interrupt for it.
///
/// See [`crate::stm32`] for more details.
///
/// # Arguments
///
/// * `name` - The name that the monotonic type will have.
/// * `tick_rate_hz` - The tick rate of the timer peripheral.
///
#[cfg(feature = "stm32_tim4")]
#[macro_export]
macro_rules! stm32_tim4_monotonic {
    ($name:ident, $tick_rate_hz:expr) => {
        $crate::__internal_create_stm32_timer_struct!($name, Tim4Backend, TIM4, $tick_rate_hz);
    };
}

/// Create a TIM5 based monotonic and register the TIM5 interrupt for it.
///
/// See [`crate::stm32`] for more details.
///
/// # Arguments
///
/// * `name` - The name that the monotonic type will have.
/// * `tick_rate_hz` - The tick rate of the timer peripheral.
///
#[cfg(feature = "stm32_tim5")]
#[macro_export]
macro_rules! stm32_tim5_monotonic {
    ($name:ident, $tick_rate_hz:expr) => {
        $crate::__internal_create_stm32_timer_struct!($name, Tim5Backend, TIM5, $tick_rate_hz);
    };
}

/// Create a TIM15 based monotonic and register the TIM15 interrupt for it.
///
/// See [`crate::stm32`] for more details.
///
/// # Arguments
///
/// * `name` - The name that the monotonic type will have.
/// * `tick_rate_hz` - The tick rate of the timer peripheral.
///
#[cfg(feature = "stm32_tim15")]
#[macro_export]
macro_rules! stm32_tim15_monotonic {
    ($name:ident, $tick_rate_hz:expr) => {
        $crate::__internal_create_stm32_timer_struct!($name, Tim15Backend, TIM15, $tick_rate_hz);
    };
}

trait TimerWord: TryFrom<u64> {
    const HALF_PERIOD_VALUE: Self;
    fn trunc_from_u64(val: u64) -> Self;
}

impl TimerWord for u8 {
    const HALF_PERIOD_VALUE: Self = 0x80;
    fn trunc_from_u64(val: u64) -> Self {
        val as Self
    }
}
impl TimerWord for u16 {
    const HALF_PERIOD_VALUE: u16 = 0x8000;
    fn trunc_from_u64(val: u64) -> Self {
        val as Self
    }
}
impl TimerWord for u32 {
    const HALF_PERIOD_VALUE: u32 = 0x8000_0000;
    fn trunc_from_u64(val: u64) -> Self {
        val as Self
    }
}
impl TimerWord for u64 {
    const HALF_PERIOD_VALUE: u64 = 0x8000_0000_0000_0000;
    fn trunc_from_u64(val: u64) -> Self {
        val as Self
    }
}

/// Returns the half-period value for a timer.
///
/// The closure argument is never invoked; it forces the CNT and CCR word
/// types to be inferred as the same `T`, causing a width mismatch between
/// the two registers to fail type-checking.
///
/// # Example
///
/// ```ignore
/// timer.ccr(0).write(|r| *r = half_period_value(|| timer.cnt().read()));
/// ```
fn half_period_value<T: TimerWord>(
    _: impl FnOnce() -> T, /* as a sanity check that the CCR width is identical to the CNT width */
) -> T {
    T::HALF_PERIOD_VALUE
}

/// Computes the CCR compare value for a target `instant`, given the current
/// counter value `now`.
///
/// If the target is in the past or would overflow the timer's range before
/// being reached, returns `0` so the compare match fires on the next
/// wrap-around rather than at a stale value.
///
/// The closure argument is never invoked; it forces the CNT and CCR word
/// types to be inferred as the same `T`, causing a width mismatch between
/// the two registers to fail type-checking.
///
/// # Example
///
/// ```ignore
/// timer.ccr(1).write(|r| {
///     *r = compute_compare_value(instant, now, || timer.cnt().read());
/// });
/// ```
fn compute_compare_value<T: TimerWord>(
    instant: u64,
    now: u64,
    _: impl FnOnce() -> T, /* as a sanity check that the CCR width is identical to the CNT width */
) -> T {
    // Since the timer may or may not overflow based on the requested compare val, we check how many ticks are left.
    // `wrapping_sub` takes care of the u64 integer overflow special case.
    let val = if T::try_from(instant.wrapping_sub(now)).is_ok() {
        instant
    } else {
        // In the past or will overflow
        0
    };

    T::trunc_from_u64(val)
}

macro_rules! make_timer {
    ($backend_name:ident, $timer:ident, $overflow:ident, $tq:ident$(, doc: ($($doc:tt)*))?) => {
        /// Monotonic timer backend implementation.
        $(
            #[cfg_attr(docsrs, doc(cfg($($doc)*)))]
        )?

        pub struct $backend_name;

        use pac::$timer;

        static $overflow: AtomicU64 = AtomicU64::new(0);
        static $tq: TimerQueue<$backend_name> = TimerQueue::new();

        impl $backend_name {
            /// Starts the timer.
            ///
            /// **Do not use this function directly.**
            ///
            /// Use the prelude macros instead.
            pub fn _start(tim_clock_hz: u32, timer_hz: u32) {
                _generated::$timer::enable();
                _generated::$timer::reset();

                $timer.cr1().modify(|r| r.set_cen(false));

                ::core::assert!((tim_clock_hz % timer_hz) == 0, "Unable to find suitable timer prescaler value!");
                let Ok(psc) = u16::try_from(tim_clock_hz / timer_hz - 1) else {
                    ::core::panic!("Clock prescaler overflowed!");
                };
                $timer.psc().write(|r| *r = psc);

                // Enable full-period interrupt.
                $timer.dier().modify(|r| r.set_uie(true));

                // Configure and enable half-period interrupt
                $timer.ccr(0).write(|r| *r = half_period_value(|| $timer.cnt().read()));
                $timer.dier().modify(|r| r.set_ccie(0, true));

                // Trigger an update event to load the prescaler value to the clock.
                $timer.egr().write(|r| r.set_ug(true));

                // Clear timer value so it is known that we are at the first half period
                $timer.cnt().write(|r| *r = 1);

                // Triggering the update event might have raised overflow interrupts.
                // Clear them to return to a known state.
                $timer.sr().write(|r| {
                    r.0 = !0;
                    r.set_uif(false);
                    r.set_ccif(0, false);
                    r.set_ccif(1, false);
                });

                $tq.initialize(Self {});
                $overflow.store(0, Ordering::SeqCst);

                // Start the counter.
                $timer.cr1().modify(|r| {
                    r.set_cen(true);
                });

                // SAFETY: We take full ownership of the peripheral and interrupt vector,
                // plus we are not using any external shared resources so we won't impact
                // basepri/source masking based critical sections.
                unsafe {
                    crate::set_monotonic_prio(_generated::NVIC_PRIO_BITS, pac::Interrupt::$timer);
                    cortex_m::peripheral::NVIC::unmask(pac::Interrupt::$timer);
                }
            }
        }

        impl TimerQueueBackend for $backend_name {
            type Ticks = u64;

            fn now() -> Self::Ticks {
                calculate_now(
                    || $overflow.load(Ordering::Relaxed),
                    || $timer.cnt().read()
                )
            }

            fn set_compare(instant: Self::Ticks) {
                let now = Self::now();

                $timer.ccr(1).write(|r| {
                    *r = compute_compare_value(instant, now, || $timer.cnt().read());
                });
            }

            fn clear_compare_flag() {
                $timer.sr().write(|r| {
                    r.0 = !0;
                    r.set_ccif(1, false);
                });
            }

            fn pend_interrupt() {
                cortex_m::peripheral::NVIC::pend(pac::Interrupt::$timer);
            }

            fn enable_timer() {
                $timer.dier().modify(|r| r.set_ccie(1, true));
            }

            fn disable_timer() {
                $timer.dier().modify(|r| r.set_ccie(1, false));
            }

            fn on_interrupt() {
                // Full period
                if $timer.sr().read().uif() {
                    $timer.sr().write(|r| {
                        r.0 = !0;
                        r.set_uif(false);
                    });
                    let prev = $overflow.fetch_add(1, Ordering::Relaxed);
                    ::core::assert!(prev % 2 == 1, "Monotonic must have missed an interrupt!");
                }
                // Half period
                if $timer.sr().read().ccif(0) {
                    $timer.sr().write(|r| {
                        r.0 = !0;
                        r.set_ccif(0, false);
                    });
                    let prev = $overflow.fetch_add(1, Ordering::Relaxed);
                    ::core::assert!(prev % 2 == 0, "Monotonic must have missed an interrupt!");
                }
            }

            fn timer_queue() -> &'static TimerQueue<$backend_name> {
                &$tq
            }
        }
    };
}

macro_rules! make_timer2 {
    ($backend_name:ident, $timer:ident, $overflow:ident, $tq:ident$(, doc: ($($doc:tt)*))?) => {
        /// Monotonic timer backend implementation.
        $(
            #[cfg_attr(docsrs, doc(cfg($($doc)*)))]
        )?

        pub struct $backend_name;

        use pac::$timer;

        static $overflow: AtomicU64 = AtomicU64::new(0);
        static $tq: TimerQueue<$backend_name> = TimerQueue::new();

        impl $backend_name {
            /// Starts the timer.
            ///
            /// **Do not use this function directly.**
            ///
            /// Use the prelude macros instead.
            pub fn _start(tim_clock_hz: u32, timer_hz: u32) {
                _generated::$timer::enable();
                _generated::$timer::reset();

                $timer.cr1().modify(|r| r.set_cen(false));

                ::core::assert!((tim_clock_hz % timer_hz) == 0, "Unable to find suitable timer prescaler value!");
                let Ok(psc) = u16::try_from(tim_clock_hz / timer_hz - 1) else {
                    ::core::panic!("Clock prescaler overflowed!");
                };
                $timer.psc().write(|r| *r = psc);

                // Enable full-period interrupt.
                $timer.dier().modify(|r| r.set_uie(true));

                // Configure and enable half-period interrupt
                $timer.ccr(0).write(|r| r.set_ccr(half_period_value(|| $timer.cnt().read().cnt())));
                $timer.dier().modify(|r| r.set_ccie(0, true));

                // Trigger an update event to load the prescaler value to the clock.
                $timer.egr().write(|r| r.set_ug(true));

                // Clear timer value so it is known that we are at the first half period
                $timer.cnt().write(|r| r.set_cnt(1));

                // Triggering the update event might have raised overflow interrupts.
                // Clear them to return to a known state.
                $timer.sr().write(|r| {
                    r.0 = !0;
                    r.set_uif(false);
                    r.set_ccif(0, false);
                    r.set_ccif(1, false);
                });

                $tq.initialize(Self {});
                $overflow.store(0, Ordering::SeqCst);

                // Start the counter.
                $timer.cr1().modify(|r| {
                    r.set_cen(true);
                });

                // SAFETY: We take full ownership of the peripheral and interrupt vector,
                // plus we are not using any external shared resources so we won't impact
                // basepri/source masking based critical sections.
                unsafe {
                    crate::set_monotonic_prio(_generated::NVIC_PRIO_BITS, pac::Interrupt::$timer);
                    cortex_m::peripheral::NVIC::unmask(pac::Interrupt::$timer);
                }
            }
        }

        impl TimerQueueBackend for $backend_name {
            type Ticks = u64;

            fn now() -> Self::Ticks {
                calculate_now(
                    || $overflow.load(Ordering::Relaxed),
                    || $timer.cnt().read().cnt()
                )
            }

            fn set_compare(instant: Self::Ticks) {
                let now = Self::now();

                $timer.ccr(1).write(|r| {
                    r.set_ccr(compute_compare_value(instant, now, || $timer.cnt().read().cnt()));
                });
            }

            fn clear_compare_flag() {
                $timer.sr().write(|r| {
                    r.0 = !0;
                    r.set_ccif(1, false);
                });
            }

            fn pend_interrupt() {
                cortex_m::peripheral::NVIC::pend(pac::Interrupt::$timer);
            }

            fn enable_timer() {
                $timer.dier().modify(|r| r.set_ccie(1, true));
            }

            fn disable_timer() {
                $timer.dier().modify(|r| r.set_ccie(1, false));
            }

            fn on_interrupt() {
                // Full period
                if $timer.sr().read().uif() {
                    $timer.sr().write(|r| {
                        r.0 = !0;
                        r.set_uif(false);
                    });
                    let prev = $overflow.fetch_add(1, Ordering::Relaxed);
                    ::core::assert!(prev % 2 == 1, "Monotonic must have missed an interrupt!");
                }
                // Half period
                if $timer.sr().read().ccif(0) {
                    $timer.sr().write(|r| {
                        r.0 = !0;
                        r.set_ccif(0, false);
                    });
                    let prev = $overflow.fetch_add(1, Ordering::Relaxed);
                    ::core::assert!(prev % 2 == 0, "Monotonic must have missed an interrupt!");
                }
            }

            fn timer_queue() -> &'static TimerQueue<$backend_name> {
                &$tq
            }
        }
    };
}

#[cfg(feature = "stm32_tim2")]
make_timer!(Tim2Backend, TIM2, TIMER2_OVERFLOWS, TIMER2_TQ);

#[cfg(feature = "stm32_tim3")]
make_timer2!(Tim3Backend, TIM3, TIMER3_OVERFLOWS, TIMER3_TQ);

#[cfg(feature = "stm32_tim4")]
make_timer2!(Tim4Backend, TIM4, TIMER4_OVERFLOWS, TIMER4_TQ);

#[cfg(feature = "stm32_tim5")]
make_timer!(Tim5Backend, TIM5, TIMER5_OVERFLOWS, TIMER5_TQ);

#[cfg(feature = "stm32_tim15")]
make_timer2!(Tim15Backend, TIM15, TIMER15_OVERFLOWS, TIMER15_TQ);