stm32f7x7_hal/
time.rs

1//! Time units
2
3use cortex_m::peripheral::DWT;
4
5use crate::rcc::Clocks;
6
7/// Bits per second
8#[derive(PartialEq, PartialOrd, Clone, Copy)]
9pub struct Bps(pub u32);
10
11/// Hertz
12#[derive(PartialEq, PartialOrd, Clone, Copy)]
13pub struct Hertz(pub u32);
14
15/// KiloHertz
16#[derive(PartialEq, PartialOrd, Clone, Copy)]
17pub struct KiloHertz(pub u32);
18
19/// MegaHertz
20#[derive(PartialEq, PartialOrd, Clone, Copy)]
21pub struct MegaHertz(pub u32);
22
23/// Extension trait that adds convenience methods to the `u32` type
24pub trait U32Ext {
25    /// Wrap in `Bps`
26    fn bps(self) -> Bps;
27
28    /// Wrap in `Hertz`
29    fn hz(self) -> Hertz;
30
31    /// Wrap in `KiloHertz`
32    fn khz(self) -> KiloHertz;
33
34    /// Wrap in `MegaHertz`
35    fn mhz(self) -> MegaHertz;
36
37    /// Wrap in `MilliSeconds`
38    fn ms(self) -> MilliSeconds;
39}
40
41impl U32Ext for u32 {
42    fn bps(self) -> Bps {
43        Bps(self)
44    }
45
46    fn hz(self) -> Hertz {
47        Hertz(self)
48    }
49
50    fn khz(self) -> KiloHertz {
51        KiloHertz(self)
52    }
53
54    fn mhz(self) -> MegaHertz {
55        MegaHertz(self)
56    }
57
58    fn ms(self) -> MilliSeconds {
59        MilliSeconds(self)
60    }
61}
62
63impl Into<Hertz> for KiloHertz {
64    fn into(self) -> Hertz {
65        Hertz(self.0 * 1_000)
66    }
67}
68
69impl Into<Hertz> for MegaHertz {
70    fn into(self) -> Hertz {
71        Hertz(self.0 * 1_000_000)
72    }
73}
74
75impl Into<KiloHertz> for MegaHertz {
76    fn into(self) -> KiloHertz {
77        KiloHertz(self.0 * 1_000)
78    }
79}
80
81/// Time unit
82#[derive(PartialEq, PartialOrd, Clone, Copy)]
83pub struct MilliSeconds(pub u32);
84
85/// A monotonic nondecreasing timer
86#[derive(Clone, Copy)]
87pub struct MonoTimer {
88    frequency: Hertz,
89}
90
91impl MonoTimer {
92    /// Creates a new `Monotonic` timer
93    pub fn new(mut dwt: DWT, clocks: Clocks) -> Self {
94        dwt.enable_cycle_counter();
95
96        // now the CYCCNT counter can't be stopped or resetted
97        drop(dwt);
98
99        MonoTimer {
100            frequency: clocks.sysclk(),
101        }
102    }
103
104    /// Returns the frequency at which the monotonic timer is operating at
105    pub fn frequency(&self) -> Hertz {
106        self.frequency
107    }
108
109    /// Returns an `Instant` corresponding to "now"
110    pub fn now(&self) -> Instant {
111        Instant {
112            now: DWT::get_cycle_count(),
113        }
114    }
115}
116
117/// A measurement of a monotonically nondecreasing clock
118#[derive(Clone, Copy)]
119pub struct Instant {
120    now: u32,
121}
122
123impl Instant {
124    /// Ticks elapsed since the `Instant` was created
125    pub fn elapsed(&self) -> u32 {
126        DWT::get_cycle_count().wrapping_sub(self.now)
127    }
128}
129