stm32l4x6_hal/
delay.rs

1//! Delays
2
3use cast::u32;
4use cortex_m::peripheral::syst::SystClkSource;
5use cortex_m::peripheral::SYST;
6use hal::blocking::delay::{DelayMs, DelayUs};
7
8use cmp;
9
10use config::SYST_MAX_RVR;
11use rcc::Clocks;
12
13/// System timer (SysTick) as a delay provider
14pub struct Delay {
15    clocks: Clocks,
16    syst: SYST,
17}
18
19impl Delay {
20    /// Configures the system timer (SysTick) as a delay provider
21    pub fn new(mut syst: SYST, clocks: Clocks) -> Self {
22        syst.set_clock_source(SystClkSource::Core);
23
24        Delay { syst, clocks }
25    }
26
27    /// Releases the system timer (SysTick) resource
28    pub fn free(self) -> SYST {
29        self.syst
30    }
31}
32
33impl DelayMs<u32> for Delay {
34    fn delay_ms(&mut self, ms: u32) {
35        self.delay_us(ms * 1_000);
36    }
37}
38
39impl DelayMs<u16> for Delay {
40    fn delay_ms(&mut self, ms: u16) {
41        self.delay_ms(u32(ms));
42    }
43}
44
45impl DelayMs<u8> for Delay {
46    fn delay_ms(&mut self, ms: u8) {
47        self.delay_ms(u32(ms));
48    }
49}
50
51impl DelayUs<u32> for Delay {
52    fn delay_us(&mut self, us: u32) {
53        let mut total_rvr = us * (self.clocks.sysclk.0 / 1_000_000);
54
55        while total_rvr != 0 {
56            let current_rvr = cmp::min(total_rvr, SYST_MAX_RVR);
57
58            self.syst.set_reload(current_rvr);
59            self.syst.clear_current();
60            self.syst.enable_counter();
61
62            // Update the tracking variable while we are waiting...
63            total_rvr -= current_rvr;
64
65            while !self.syst.has_wrapped() {}
66
67            self.syst.disable_counter();
68        }
69    }
70}
71
72impl DelayUs<u16> for Delay {
73    fn delay_us(&mut self, us: u16) {
74        self.delay_us(u32(us))
75    }
76}
77
78impl DelayUs<u8> for Delay {
79    fn delay_us(&mut self, us: u8) {
80        self.delay_us(u32(us))
81    }
82}