Skip to main content

ws63_hal/
delay.rs

1//! Blocking delay driver for WS63.
2//!
3//! Uses busy-loop timing based on the system clock frequency.
4//! Implements `embedded_hal::delay::DelayNs`.
5
6use crate::soc::ws63::SYSTEM_CLOCK_HZ;
7
8/// Delay driver using busy-wait loops.
9pub struct Delay;
10
11impl Delay {
12    /// Create a new delay driver.
13    #[allow(clippy::new_without_default)]
14    pub const fn new() -> Self {
15        Delay
16    }
17
18    /// Busy-wait for the given number of microseconds.
19    pub fn delay_micros(&self, us: u32) {
20        // Each loop iteration is roughly 3 cycles (decrement, compare, branch)
21        let cycles_per_loop: u32 = 3;
22        let cycles = (SYSTEM_CLOCK_HZ as u64 * us as u64 / 1_000_000) as u32;
23        let loops = cycles / cycles_per_loop;
24        for _ in 0..loops {
25            core::hint::spin_loop();
26        }
27    }
28
29    /// Busy-wait for the given number of milliseconds.
30    pub fn delay_millis(&self, ms: u32) {
31        for _ in 0..ms {
32            self.delay_micros(1_000);
33        }
34    }
35}
36
37impl embedded_hal::delay::DelayNs for Delay {
38    fn delay_ns(&mut self, ns: u32) {
39        // Use microsecond granularity, rounding up
40        let us = ns.div_ceil(1_000);
41        self.delay_micros(us);
42    }
43
44    fn delay_us(&mut self, us: u32) {
45        self.delay_micros(us);
46    }
47
48    fn delay_ms(&mut self, ms: u32) {
49        self.delay_millis(ms);
50    }
51}