1use cortex_m::peripheral::DWT;
4
5use rcc::Clocks;
6
7#[derive(Clone, Copy, Debug)]
9pub struct Bps(pub u32);
10
11#[derive(Clone, Copy, Debug)]
13pub struct Hertz(pub u32);
14
15#[derive(Clone, Copy, Debug)]
17pub struct KiloHertz(pub u32);
18
19#[derive(Clone, Copy, Debug)]
21pub struct MegaHertz(pub u32);
22
23pub trait U32Ext {
25 fn bps(self) -> Bps;
27
28 fn hz(self) -> Hertz;
30
31 fn khz(self) -> KiloHertz;
33
34 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#[derive(Clone, Copy)]
94pub struct MonoTimer {
95 frequency: Hertz,
96}
97
98impl MonoTimer {
99 pub fn new(mut dwt: DWT, clocks: Clocks) -> Self {
101 dwt.enable_cycle_counter();
102
103 drop(dwt);
105
106 MonoTimer {
107 frequency: clocks.sysclk(),
108 }
109 }
110
111 pub fn frequency(&self) -> Hertz {
113 self.frequency
114 }
115
116 pub fn now(&self) -> Instant {
118 Instant {
119 now: DWT::get_cycle_count(),
120 }
121 }
122}
123
124#[derive(Clone, Copy)]
126pub struct Instant {
127 now: u32,
128}
129
130impl Instant {
131 pub fn elapsed(&self) -> u32 {
133 DWT::get_cycle_count().wrapping_sub(self.now)
134 }
135}