taskette_utils/
delay.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! `embedded-hal`-compatible delay that yields CPU to other tasks instead of busy looping.
6//! The precision is limited by the tick frequency setting of the scheduler (usually order of a millisecond or more).
7use taskette::{Error, scheduler::get_config, timer::{current_time, wait_until}};
8
9#[derive(Clone)]
10pub struct Delay {
11    tick_freq: u32,
12}
13
14impl Delay {
15    pub fn new() -> Result<Self, Error> {
16        let tick_freq = get_config()?.tick_freq;
17
18        Ok(Self { tick_freq })
19    }
20
21    pub fn delay_ticks(&mut self, ticks: u64) {
22        let now = current_time().expect("Failed to acquire current time");
23        wait_until(now + ticks).expect("Failed to register timeout");
24    }
25}
26
27impl embedded_hal::delay::DelayNs for Delay {
28    fn delay_ns(&mut self, ns: u32) {
29        self.delay_ticks(((ns * self.tick_freq) as u64).div_ceil(1_000_000_000));
30    }
31
32    fn delay_us(&mut self, us: u32) {
33        self.delay_ticks(((us * self.tick_freq) as u64).div_ceil(1_000_000));
34    }
35
36    fn delay_ms(&mut self, ms: u32) {
37        self.delay_ticks(((ms * self.tick_freq) as u64).div_ceil(1_000));
38    }
39}