1use cast::u32;
4use cortex_m::peripheral::syst::SystClkSource;
5use cortex_m::peripheral::SYST;
6
7use crate::rcc::Clocks;
8use embedded_hal::blocking::delay::{DelayMs, DelayUs};
9
10pub struct Delay {
12 clocks: Clocks,
13 syst: SYST,
14}
15
16impl Delay {
17 pub fn new(mut syst: SYST, clocks: Clocks) -> Self {
19 syst.set_clock_source(SystClkSource::External);
20
21 Delay { syst, clocks }
22 }
23
24 pub fn free(self) -> SYST {
26 self.syst
27 }
28}
29
30impl DelayMs<u32> for Delay {
31 fn delay_ms(&mut self, ms: u32) {
32 self.delay_us(ms * 1_000);
33 }
34}
35
36impl DelayMs<u16> for Delay {
37 fn delay_ms(&mut self, ms: u16) {
38 self.delay_ms(u32(ms));
39 }
40}
41
42impl DelayMs<u8> for Delay {
43 fn delay_ms(&mut self, ms: u8) {
44 self.delay_ms(u32(ms));
45 }
46}
47
48impl DelayUs<u32> for Delay {
49 fn delay_us(&mut self, us: u32) {
50 const MAX_RVR: u32 = 0x00FF_FFFF;
52
53 let mut total_rvr = us * (self.clocks.hclk().0 / 8_000_000);
54
55 while total_rvr != 0 {
56 let current_rvr = if total_rvr <= MAX_RVR {
57 total_rvr
58 } else {
59 MAX_RVR
60 };
61
62 self.syst.set_reload(current_rvr);
63 self.syst.clear_current();
64 self.syst.enable_counter();
65
66 total_rvr -= current_rvr;
68
69 while !self.syst.has_wrapped() {}
70
71 self.syst.disable_counter();
72 }
73 }
74}
75
76impl DelayUs<u16> for Delay {
77 fn delay_us(&mut self, us: u16) {
78 self.delay_us(u32(us))
79 }
80}
81
82impl DelayUs<u8> for Delay {
83 fn delay_us(&mut self, us: u8) {
84 self.delay_us(u32(us))
85 }
86}