1use cortex_m::peripheral::DWT;
4
5use crate::rcc::Clocks;
6
7#[derive(PartialEq, PartialOrd, Clone, Copy)]
9pub struct Bps(pub u32);
10
11#[derive(PartialEq, PartialOrd, Clone, Copy)]
13pub struct Hertz(pub u32);
14
15#[derive(PartialEq, PartialOrd, Clone, Copy)]
17pub struct KiloHertz(pub u32);
18
19#[derive(PartialEq, PartialOrd, 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 fn ms(self) -> MilliSeconds;
39}
40
41impl U32Ext for u32 {
42 fn bps(self) -> Bps {
43 Bps(self)
44 }
45
46 fn hz(self) -> Hertz {
47 Hertz(self)
48 }
49
50 fn khz(self) -> KiloHertz {
51 KiloHertz(self)
52 }
53
54 fn mhz(self) -> MegaHertz {
55 MegaHertz(self)
56 }
57
58 fn ms(self) -> MilliSeconds {
59 MilliSeconds(self)
60 }
61}
62
63impl Into<Hertz> for KiloHertz {
64 fn into(self) -> Hertz {
65 Hertz(self.0 * 1_000)
66 }
67}
68
69impl Into<Hertz> for MegaHertz {
70 fn into(self) -> Hertz {
71 Hertz(self.0 * 1_000_000)
72 }
73}
74
75impl Into<KiloHertz> for MegaHertz {
76 fn into(self) -> KiloHertz {
77 KiloHertz(self.0 * 1_000)
78 }
79}
80
81#[derive(PartialEq, PartialOrd, Clone, Copy)]
83pub struct MilliSeconds(pub u32);
84
85#[derive(Clone, Copy)]
87pub struct MonoTimer {
88 frequency: Hertz,
89}
90
91impl MonoTimer {
92 pub fn new(mut dwt: DWT, clocks: Clocks) -> Self {
94 dwt.enable_cycle_counter();
95
96 drop(dwt);
98
99 MonoTimer {
100 frequency: clocks.sysclk(),
101 }
102 }
103
104 pub fn frequency(&self) -> Hertz {
106 self.frequency
107 }
108
109 pub fn now(&self) -> Instant {
111 Instant {
112 now: DWT::get_cycle_count(),
113 }
114 }
115}
116
117#[derive(Clone, Copy)]
119pub struct Instant {
120 now: u32,
121}
122
123impl Instant {
124 pub fn elapsed(&self) -> u32 {
126 DWT::get_cycle_count().wrapping_sub(self.now)
127 }
128}
129