esp_hal/delay.rs
1//! # Delay
2//!
3//! ## Overview
4//!
5//! The Delay driver provides blocking delay functionalities using the
6//! [`Instant`] struct.
7//!
8//! ## Configuration
9//!
10//! The delays are implemented in a "best-effort" way, meaning that the CPU will
11//! block for at least the amount of time specified, but accuracy can be
12//! affected by many factors, including interrupt usage.
13//!
14//! ## Usage
15//!
16//! This module implements the blocking [DelayNs] trait from [embedded-hal].
17//!
18//! ## Examples
19//! ### Delay for 1 second
20//! ```rust, no_run
21#![doc = crate::before_snippet!()]
22//! # use esp_hal::delay::Delay;
23//! # use embedded_hal::delay::DelayNs;
24//! let mut delay = Delay::new();
25//!
26//! delay.delay_ms(1000 as u32);
27//! # Ok(())
28//! # }
29//! ```
30//!
31//! [DelayNs]: https://docs.rs/embedded-hal/1.0.0/embedded_hal/delay/trait.DelayNs.html
32//! [embedded-hal]: https://docs.rs/embedded-hal/1.0.0/embedded_hal/delay/index.html
33
34use crate::time::{Duration, Instant};
35
36/// Delay driver, using [`Instant`].
37#[derive(Clone, Copy, Default)]
38#[non_exhaustive]
39pub struct Delay;
40
41impl embedded_hal::delay::DelayNs for Delay {
42 fn delay_ns(&mut self, ns: u32) {
43 self.delay_nanos(ns);
44 }
45}
46
47impl Delay {
48 /// Creates a new `Delay` instance.
49 pub const fn new() -> Self {
50 Self {}
51 }
52
53 /// Delay for the specified time
54 pub fn delay(&self, delay: Duration) {
55 let start = Instant::now();
56
57 while start.elapsed() < delay {}
58 }
59
60 /// Delay for the specified number of milliseconds
61 pub fn delay_millis(&self, ms: u32) {
62 self.delay(Duration::from_millis(ms as u64));
63 }
64
65 /// Delay for the specified number of microseconds
66 pub fn delay_micros(&self, us: u32) {
67 self.delay(Duration::from_micros(us as u64));
68 }
69
70 /// Delay for the specified number of nanoseconds
71 pub fn delay_nanos(&self, ns: u32) {
72 self.delay(Duration::from_micros(ns.div_ceil(1000) as u64));
73 }
74}