tm4c_hal/
time.rs

1//! Time units
2
3use cortex_m::peripheral::DWT;
4
5/// Bits per second
6#[derive(Clone, Copy)]
7pub struct Bps(pub u32);
8
9/// Hertz
10#[derive(Clone, Copy)]
11pub struct Hertz(pub u32);
12
13/// KiloHertz
14#[derive(Clone, Copy)]
15pub struct KiloHertz(pub u32);
16
17/// MegaHertz
18#[derive(Clone, Copy)]
19pub struct MegaHertz(pub u32);
20
21/// Extension trait that adds convenience methods to the `u32` type
22pub trait U32Ext {
23    /// Wrap in `Bps`
24    fn bps(self) -> Bps;
25
26    /// Wrap in `Hertz`
27    fn hz(self) -> Hertz;
28
29    /// Wrap in `KiloHertz`
30    fn khz(self) -> KiloHertz;
31
32    /// Wrap in `MegaHertz`
33    fn mhz(self) -> MegaHertz;
34}
35
36impl U32Ext for u32 {
37    fn bps(self) -> Bps {
38        Bps(self)
39    }
40
41    fn hz(self) -> Hertz {
42        Hertz(self)
43    }
44
45    fn khz(self) -> KiloHertz {
46        KiloHertz(self)
47    }
48
49    fn mhz(self) -> MegaHertz {
50        MegaHertz(self)
51    }
52}
53
54impl Into<Hertz> for KiloHertz {
55    fn into(self) -> Hertz {
56        Hertz(self.0 * 1_000)
57    }
58}
59
60impl Into<Hertz> for MegaHertz {
61    fn into(self) -> Hertz {
62        Hertz(self.0 * 1_000_000)
63    }
64}
65
66impl Into<KiloHertz> for MegaHertz {
67    fn into(self) -> KiloHertz {
68        KiloHertz(self.0 * 1_000)
69    }
70}
71
72/// A monotonic nondecreasing timer
73#[derive(Clone, Copy)]
74pub struct MonoTimer {
75    frequency: Hertz,
76}
77
78impl MonoTimer {
79    /// Returns the frequency at which the monotonic timer is operating at
80    pub fn frequency(self) -> Hertz {
81        self.frequency
82    }
83
84    /// Returns an `Instant` corresponding to "now"
85    pub fn now(self) -> Instant {
86        Instant {
87            now: DWT::get_cycle_count(),
88        }
89    }
90}
91
92/// A measurement of a monotonically nondecreasing clock
93#[derive(Clone, Copy)]
94pub struct Instant {
95    now: u32,
96}
97
98impl Instant {
99    /// Ticks elapsed since the `Instant` was created
100    pub fn elapsed(self) -> u32 {
101        DWT::get_cycle_count().wrapping_sub(self.now)
102    }
103}