tm1637_embedded_hal/demo/
asynch.rs

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
//! Asynchronous demo module.
//!
//! This module is only available when the `demo` and `async` features of this
//! library are activated.

use embedded_hal::digital::OutputPin;
use embedded_hal_async::delay::DelayNs;

use crate::{asynch::TM1637, mappings::DigitBits};

/// Asynchronous demo.
pub struct Demo<CLK, DIO, DELAY, ERR>
where
    CLK: OutputPin<Error = ERR>,
    DIO: OutputPin<Error = ERR>,
    DELAY: DelayNs,
{
    device: TM1637<CLK, DIO, DELAY>,
    delay: DELAY,
}
impl<CLK, DIO, DELAY, ERR> Demo<CLK, DIO, DELAY, ERR>
where
    ERR: core::fmt::Debug,
    CLK: OutputPin<Error = ERR>,
    DIO: OutputPin<Error = ERR>,
    DELAY: DelayNs,
{
    /// Create a new demo instance.
    pub fn new(device: TM1637<CLK, DIO, DELAY>, delay: DELAY) -> Self {
        Self { device, delay }
    }

    /// Create a timer that counts down from 9 to 0 at the first position.
    pub async fn timer(&mut self) -> Result<(), ERR> {
        for i in (0..=9).rev() {
            self.device
                .write_segments_raw(0, &[DigitBits::from_digit(i) as u8])
                .await?;
            self.delay.delay_ms(1000).await;
        }

        self.device
            .write_segments_raw(
                0,
                &[
                    DigitBits::Zero,
                    DigitBits::Zero,
                    DigitBits::Zero,
                    DigitBits::Zero,
                ]
                .map(|d| d as u8),
            )
            .await?;

        for _ in 0..5 {
            self.delay.delay_ms(300).await;
            self.device.off().await?;
            self.delay.delay_ms(300).await;
            self.device.on().await?;
        }

        self.delay.delay_ms(300).await;

        self.device.clear().await?;

        Ok(())
    }
}