embassy_time/
delay.rs

1use core::future::Future;
2
3use super::{Duration, Instant};
4use crate::Timer;
5
6/// Blocks for at least `duration`.
7pub fn block_for(duration: Duration) {
8    let expires_at = Instant::now() + duration;
9    while Instant::now() < expires_at {}
10}
11
12/// Type implementing async delays and blocking `embedded-hal` delays.
13///
14/// The delays are implemented in a "best-effort" way, meaning that the cpu will block for at least
15/// the amount provided, but accuracy can be affected by many factors, including interrupt usage.
16/// Make sure to use a suitable tick rate for your use case. The tick rate is defined by the currently
17/// active driver.
18#[derive(Clone, Debug)]
19#[cfg_attr(feature = "defmt", derive(defmt::Format))]
20pub struct Delay;
21
22impl embedded_hal_1::delay::DelayNs for Delay {
23    fn delay_ns(&mut self, ns: u32) {
24        block_for(Duration::from_nanos(ns as u64))
25    }
26
27    fn delay_us(&mut self, us: u32) {
28        block_for(Duration::from_micros(us as u64))
29    }
30
31    fn delay_ms(&mut self, ms: u32) {
32        block_for(Duration::from_millis(ms as u64))
33    }
34}
35
36impl embedded_hal_async::delay::DelayNs for Delay {
37    fn delay_ns(&mut self, ns: u32) -> impl Future<Output = ()> {
38        Timer::after_nanos(ns as _)
39    }
40
41    fn delay_us(&mut self, us: u32) -> impl Future<Output = ()> {
42        Timer::after_micros(us as _)
43    }
44
45    fn delay_ms(&mut self, ms: u32) -> impl Future<Output = ()> {
46        Timer::after_millis(ms as _)
47    }
48}
49
50impl embedded_hal_02::blocking::delay::DelayMs<u8> for Delay {
51    fn delay_ms(&mut self, ms: u8) {
52        block_for(Duration::from_millis(ms as u64))
53    }
54}
55
56impl embedded_hal_02::blocking::delay::DelayMs<u16> for Delay {
57    fn delay_ms(&mut self, ms: u16) {
58        block_for(Duration::from_millis(ms as u64))
59    }
60}
61
62impl embedded_hal_02::blocking::delay::DelayMs<u32> for Delay {
63    fn delay_ms(&mut self, ms: u32) {
64        block_for(Duration::from_millis(ms as u64))
65    }
66}
67
68impl embedded_hal_02::blocking::delay::DelayUs<u8> for Delay {
69    fn delay_us(&mut self, us: u8) {
70        block_for(Duration::from_micros(us as u64))
71    }
72}
73
74impl embedded_hal_02::blocking::delay::DelayUs<u16> for Delay {
75    fn delay_us(&mut self, us: u16) {
76        block_for(Duration::from_micros(us as u64))
77    }
78}
79
80impl embedded_hal_02::blocking::delay::DelayUs<u32> for Delay {
81    fn delay_us(&mut self, us: u32) {
82        block_for(Duration::from_micros(us as u64))
83    }
84}