1use cortex_m::peripheral::DWT;
4
5use rcc::Clocks;
6
7#[derive(Clone, Copy)]
9pub struct Bps(pub u32);
10
11#[derive(Clone, Copy)]
13pub struct Hertz(pub u32);
14
15#[derive(Clone, Copy)]
17pub struct KiloHertz(pub u32);
18
19#[derive(Clone, Copy)]
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
74#[derive(Clone, Copy)]
76pub struct MonoTimer {
77 frequency: Hertz,
78}
79
80impl MonoTimer {
81 pub fn new(mut dwt: DWT, clocks: Clocks) -> Self {
83 dwt.enable_cycle_counter();
84
85 drop(dwt);
87
88 MonoTimer {
89 frequency: clocks.sysclk(),
90 }
91 }
92
93 pub fn frequency(&self) -> Hertz {
95 self.frequency
96 }
97
98 pub fn now(&self) -> Instant {
100 Instant {
101 now: DWT::get_cycle_count(),
102 }
103 }
104}
105
106#[derive(Clone, Copy)]
108pub struct Instant {
109 now: u32,
110}
111
112impl Instant {
113 pub fn elapsed(&self) -> u32 {
115 DWT::get_cycle_count().wrapping_sub(self.now)
116 }
117}