embassy/embassy-time/src/delay.rs

97 lines
2.5 KiB
Rust
Raw Normal View History

use super::{Duration, Instant};
/// Blocks for at least `duration`.
pub fn block_for(duration: Duration) {
let expires_at = Instant::now() + duration;
while Instant::now() < expires_at {}
}
2021-07-12 03:31:56 +02:00
/// Type implementing async delays and blocking `embedded-hal` delays.
///
/// The delays are implemented in a "best-effort" way, meaning that the cpu will block for at least
/// the amount provided, but accuracy can be affected by many factors, including interrupt usage.
2021-08-24 22:46:07 +02:00
/// Make sure to use a suitable tick rate for your use case. The tick rate is defined by the currently
/// active driver.
pub struct Delay;
#[cfg(feature = "unstable-traits")]
mod eh1 {
use super::*;
2023-11-29 16:37:07 +01:00
impl embedded_hal_1::delay::DelayNs for Delay {
fn delay_ns(&mut self, ns: u32) {
block_for(Duration::from_nanos(ns as u64))
}
2023-04-06 22:25:24 +02:00
fn delay_us(&mut self, us: u32) {
block_for(Duration::from_micros(us as u64))
}
2023-04-06 22:25:24 +02:00
fn delay_ms(&mut self, ms: u32) {
block_for(Duration::from_millis(ms as u64))
}
}
}
#[cfg(all(feature = "unstable-traits", feature = "nightly"))]
mod eha {
use super::*;
use crate::Timer;
2023-11-29 16:37:07 +01:00
impl embedded_hal_async::delay::DelayNs for Delay {
async fn delay_ns(&mut self, ns: u32) {
Timer::after_nanos(ns as _).await
}
async fn delay_us(&mut self, us: u32) {
Timer::after_micros(us as _).await
}
2023-11-29 16:37:07 +01:00
async fn delay_ms(&mut self, ms: u32) {
Timer::after_millis(ms as _).await
}
}
}
mod eh02 {
use embedded_hal_02::blocking::delay::{DelayMs, DelayUs};
2022-06-12 22:15:44 +02:00
use super::*;
impl DelayMs<u8> for Delay {
fn delay_ms(&mut self, ms: u8) {
block_for(Duration::from_millis(ms as u64))
}
}
impl DelayMs<u16> for Delay {
fn delay_ms(&mut self, ms: u16) {
block_for(Duration::from_millis(ms as u64))
}
}
impl DelayMs<u32> for Delay {
fn delay_ms(&mut self, ms: u32) {
block_for(Duration::from_millis(ms as u64))
}
}
impl DelayUs<u8> for Delay {
fn delay_us(&mut self, us: u8) {
block_for(Duration::from_micros(us as u64))
}
}
impl DelayUs<u16> for Delay {
fn delay_us(&mut self, us: u16) {
block_for(Duration::from_micros(us as u64))
}
}
impl DelayUs<u32> for Delay {
fn delay_us(&mut self, us: u32) {
block_for(Duration::from_micros(us as u64))
}
}
}