stm32f429_hal/
time.rs

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