stm32f30x_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)]
9pub struct Bps(pub u32);
10
11/// Hertz
12#[derive(Clone, Copy)]
13pub struct Hertz(pub u32);
14
15/// KiloHertz
16#[derive(Clone, Copy)]
17pub struct KiloHertz(pub u32);
18
19/// MegaHertz
20#[derive(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
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
74/// A monotonic nondecreasing timer
75#[derive(Clone, Copy)]
76pub struct MonoTimer {
77    frequency: Hertz,
78}
79
80impl MonoTimer {
81    /// Creates a new `Monotonic` timer
82    pub fn new(mut dwt: DWT, clocks: Clocks) -> Self {
83        dwt.enable_cycle_counter();
84
85        // now the CYCCNT counter can't be stopped or resetted
86        drop(dwt);
87
88        MonoTimer {
89            frequency: clocks.sysclk(),
90        }
91    }
92
93    /// Returns the frequency at which the monotonic timer is operating at
94    pub fn frequency(&self) -> Hertz {
95        self.frequency
96    }
97
98    /// Returns an `Instant` corresponding to "now"
99    pub fn now(&self) -> Instant {
100        Instant {
101            now: DWT::get_cycle_count(),
102        }
103    }
104}
105
106/// A measurement of a monotonically nondecreasing clock
107#[derive(Clone, Copy)]
108pub struct Instant {
109    now: u32,
110}
111
112impl Instant {
113    /// Ticks elapsed since the `Instant` was created
114    pub fn elapsed(&self) -> u32 {
115        DWT::get_cycle_count().wrapping_sub(self.now)
116    }
117}