1
#![cfg_attr(docsrs, procmacros::doc_replace)]
2
//! # Delay
3
//!
4
//! ## Overview
5
//!
6
//! The Delay driver provides blocking delay functionalities using the
7
//! [`Instant`] struct.
8
//!
9
//! ## Configuration
10
//!
11
//! The delays are implemented in a "best-effort" way, meaning that the CPU will
12
//! block for at least the amount of time specified, but accuracy can be
13
//! affected by many factors, including interrupt usage.
14
//!
15
//! ## Usage
16
//!
17
//! This module implements the blocking [DelayNs] trait from [embedded-hal].
18
//!
19
//! ## Examples
20
//! ### Delay for 1 second
21
//! ```rust, no_run
22
//! # {before_snippet}
23
//! use embedded_hal::delay::DelayNs;
24
//! use esp_hal::delay::Delay;
25
//! let mut delay = Delay::new();
26
//!
27
//! delay.delay_ms(1000 as u32);
28
//! # {after_snippet}
29
//! ```
30
//! [DelayNs]: https://docs.rs/embedded-hal/1.0.0/embedded_hal/delay/trait.DelayNs.html
31
//! [embedded-hal]: https://docs.rs/embedded-hal/1.0.0/embedded_hal/delay/index.html
32

            
33
use crate::time::{Duration, Instant};
34

            
35
/// Delay driver that uses [`Instant`].
36
#[derive(Clone, Copy, Default)]
37
#[non_exhaustive]
38
pub struct Delay;
39

            
40
impl embedded_hal::delay::DelayNs for Delay {
41
    fn delay_ns(&mut self, ns: u32) {
42
        self.delay_nanos(ns);
43
    }
44
}
45

            
46
impl Delay {
47
    /// Creates a new `Delay` instance.
48
    pub const fn new() -> Self {
49
        Self {}
50
    }
51

            
52
    /// Delays for the specified time.
53
463
    pub fn delay(&self, delay: Duration) {
54
        let start = Instant::now();
55

            
56
5732359
        while start.elapsed() < delay {}
57
463
    }
58

            
59
    /// Delays for the specified number of milliseconds.
60
424
    pub fn delay_millis(&self, ms: u32) {
61
424
        self.delay(Duration::from_millis(ms as u64));
62
    }
63

            
64
    /// Delays for the specified number of microseconds.
65
4
    pub fn delay_micros(&self, us: u32) {
66
4
        self.delay(Duration::from_micros(us as u64));
67
    }
68

            
69
    /// Delays for the specified number of nanoseconds.
70
5
    pub fn delay_nanos(&self, ns: u32) {
71
5
        self.delay(Duration::from_micros(ns.div_ceil(1000) as u64));
72
    }
73
}