1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//! Implementation of [`embedded-hal`] delay traits
//!
//! [`embedded-hal`]: https://docs.rs/embedded-hal

use cast::{u32, u64};
use core::convert::Infallible;
use embedded_hal::delay::blocking::{DelayMs, DelayUs};
use std::thread;
use std::time::Duration;

/// Empty struct that provides delay functionality on top of `thread::sleep`
pub struct Delay;

impl DelayUs<u8> for Delay {
    type Error = Infallible;

    fn delay_us(&mut self, n: u8) -> Result<(), Self::Error> {
        thread::sleep(Duration::new(0, u32(n) * 1000));
        Ok(())
    }
}

impl DelayUs<u16> for Delay {
    type Error = Infallible;

    fn delay_us(&mut self, n: u16) -> Result<(), Self::Error> {
        thread::sleep(Duration::new(0, u32(n) * 1000));
        Ok(())
    }
}

impl DelayUs<u32> for Delay {
    type Error = Infallible;

    fn delay_us(&mut self, n: u32) -> Result<(), Self::Error> {
        let secs = n / 1_000_000;
        let nsecs = (n % 1_000_000) * 1_000;

        thread::sleep(Duration::new(u64(secs), nsecs));
        Ok(())
    }
}

impl DelayUs<u64> for Delay {
    type Error = Infallible;

    fn delay_us(&mut self, n: u64) -> Result<(), Self::Error> {
        let secs = n / 1_000_000;
        let nsecs = ((n % 1_000_000) * 1_000) as u32;

        thread::sleep(Duration::new(secs, nsecs));
        Ok(())
    }
}

impl DelayMs<u8> for Delay {
    type Error = Infallible;

    fn delay_ms(&mut self, n: u8) -> Result<(), Self::Error> {
        thread::sleep(Duration::from_millis(u64(n)));
        Ok(())
    }
}

impl DelayMs<u16> for Delay {
    type Error = Infallible;

    fn delay_ms(&mut self, n: u16) -> Result<(), Self::Error> {
        thread::sleep(Duration::from_millis(u64(n)));
        Ok(())
    }
}

impl DelayMs<u32> for Delay {
    type Error = Infallible;

    fn delay_ms(&mut self, n: u32) -> Result<(), Self::Error> {
        thread::sleep(Duration::from_millis(u64(n)));
        Ok(())
    }
}

impl DelayMs<u64> for Delay {
    type Error = Infallible;

    fn delay_ms(&mut self, n: u64) -> Result<(), Self::Error> {
        thread::sleep(Duration::from_millis(n));
        Ok(())
    }
}