Skip to main content

ch32_hal/delay/
impl_qingke_v2_v4.rs

1//! SYSTICK based delay implementation for Qingke V2 and V4
2
3use pac::systick::vals;
4
5use crate::pac;
6use crate::pac::SYSTICK;
7
8/// A delay provided by the SysTick core peripheral
9///
10/// This requires SysTick to be set up and running.
11/// Assumes conditions: upcount, hclk.
12/// hclk/8 is not accurate enough for ns delays.
13pub struct Delay;
14
15static mut P_US: u32 = 0;
16static mut P_MS: u32 = 0;
17
18impl Delay {
19    /// Init Systick.
20    ///
21    /// # Safety
22    ///
23    /// This function is unsafe because it conflicts with embassy's systick time dirver.
24    /// Only one of them can be used.
25    pub(crate) unsafe fn init() {
26        let sysclk = crate::rcc::clocks().hclk.0;
27
28        unsafe {
29            P_US = sysclk / 1_000_000;
30            P_MS = sysclk / 1_000;
31        }
32    }
33
34    pub fn delay_us(&mut self, ns: u32) {
35        SYSTICK.sr().modify(|w| w.set_cntif(false));
36
37        let i = ns * unsafe { P_US };
38
39        SYSTICK.cmpl().write_value(i);
40        SYSTICK.cntl().write_value(0);
41        SYSTICK.ctlr().modify(|w| {
42            w.set_stclk(vals::Stclk::HCLK);
43            w.set_ste(true);
44        });
45
46        while SYSTICK.sr().read().cntif() == false {}
47        SYSTICK.ctlr().modify(|w| w.set_ste(false));
48    }
49
50    #[inline]
51    pub fn delay_ms(&mut self, mut ms: u32) {
52        // 4294967 is the highest u32 value which you can multiply by 1000 without overflow
53        while ms > 4294967 {
54            self.delay_us(4294967000u32);
55            ms -= 4294967;
56        }
57        self.delay_us(ms * 1_000);
58    }
59}
60
61impl embedded_hal::delay::DelayNs for Delay {
62    #[inline]
63    fn delay_ns(&mut self, ns: u32) {
64        // from the rp2040-hal:
65        let us = ns / 1000 + if ns % 1000 == 0 { 0 } else { 1 };
66        // With rustc 1.73, this can be replaced by:
67        // let us = ns.div_ceil(1000);
68        Delay::delay_us(self, us)
69    }
70
71    #[inline]
72    fn delay_us(&mut self, us: u32) {
73        Delay::delay_us(self, us)
74    }
75
76    #[inline]
77    fn delay_ms(&mut self, ms: u32) {
78        Delay::delay_ms(self, ms)
79    }
80}