1use crate::{sysctl::Clocks, time::Hertz};
4use cortex_m::peripheral::{syst::SystClkSource, SYST};
5use embedded_hal::blocking::delay::{DelayMs, DelayUs};
6
7pub struct Delay {
9 sysclk: Hertz,
10 syst: SYST,
11}
12
13impl Delay {
14 pub fn new(mut syst: SYST, clocks: &Clocks) -> Self {
16 syst.set_clock_source(SystClkSource::Core);
17
18 Delay {
19 syst,
20 sysclk: clocks.sysclk,
21 }
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(cast::u32(ms));
39 }
40}
41
42impl DelayMs<u8> for Delay {
43 fn delay_ms(&mut self, ms: u8) {
44 self.delay_ms(cast::u32(ms));
45 }
46}
47
48impl DelayUs<u32> for Delay {
49 fn delay_us(&mut self, us: u32) {
50 let mut rvr = us * (self.sysclk.0 / 1_000_000);
52 rvr += (us * ((self.sysclk.0 % 1_000_000) / 1_000)) / 1_000;
53 rvr += (us * (self.sysclk.0 % 1_000)) / 1_000_000;
54
55 while rvr >= 1 << 24 {
56 self.syst.set_reload((1 << 24) - 1);
57 self.syst.clear_current();
58 self.syst.enable_counter();
59 while !self.syst.has_wrapped() {}
60 self.syst.disable_counter();
61 rvr -= 1 << 24;
62 }
63
64 assert!(rvr < (1 << 24));
65 self.syst.set_reload(rvr);
66 self.syst.clear_current();
67 self.syst.enable_counter();
68 while !self.syst.has_wrapped() {}
69 self.syst.disable_counter();
70 }
71}
72
73impl DelayUs<u16> for Delay {
74 fn delay_us(&mut self, us: u16) {
75 self.delay_us(cast::u32(us))
76 }
77}
78
79impl DelayUs<u8> for Delay {
80 fn delay_us(&mut self, us: u8) {
81 self.delay_us(cast::u32(us))
82 }
83}