ch32_hal/delay/
impl_qingke_v2_v4.rs1use pac::systick::vals;
4
5use crate::pac;
6use crate::pac::SYSTICK;
7
8pub struct Delay;
14
15static mut P_US: u32 = 0;
16static mut P_MS: u32 = 0;
17
18impl Delay {
19 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 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 let us = ns / 1000 + if ns % 1000 == 0 { 0 } else { 1 };
66 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}