stm32l4xx_hal/
time.rs

1//! Time units
2
3pub use fugit::{
4    HertzU32 as Hertz, KilohertzU32 as KiloHertz, MegahertzU32 as MegaHertz,
5    MicrosDurationU32 as MicroSeconds, MillisDurationU32 as MilliSeconds,
6};
7
8use crate::rcc::Clocks;
9use cortex_m::peripheral::DWT;
10
11/// Bits per second
12#[derive(Clone, Copy, Debug)]
13pub struct Bps(pub u32);
14
15/// Extension trait that adds convenience methods to the `u32` type
16pub trait U32Ext {
17    /// Wrap in `Bps`
18    fn bps(self) -> Bps;
19}
20
21impl U32Ext for u32 {
22    fn bps(self) -> Bps {
23        Bps(self)
24    }
25}
26
27/// A monotonic nondecreasing timer
28#[derive(Clone, Copy, Debug)]
29pub struct MonoTimer {
30    frequency: Hertz,
31}
32
33impl MonoTimer {
34    /// Creates a new `Monotonic` timer
35    pub fn new(mut dwt: DWT, clocks: Clocks) -> Self {
36        dwt.enable_cycle_counter();
37
38        // now the CYCCNT counter can't be stopped or resetted
39        drop(dwt);
40
41        MonoTimer {
42            frequency: clocks.sysclk(),
43        }
44    }
45
46    /// Returns the frequency at which the monotonic timer is operating at
47    pub fn frequency(&self) -> Hertz {
48        self.frequency
49    }
50
51    /// Returns an `Instant` corresponding to "now"
52    pub fn now(&self) -> Instant {
53        Instant {
54            now: DWT::cycle_count(),
55        }
56    }
57}
58
59/// A measurement of a monotonically nondecreasing clock
60#[derive(Clone, Copy, Debug)]
61pub struct Instant {
62    now: u32,
63}
64
65impl Instant {
66    /// Ticks elapsed since the `Instant` was created
67    pub fn elapsed(&self) -> u32 {
68        DWT::cycle_count().wrapping_sub(self.now)
69    }
70}