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