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
91
92
#![no_std]

use embedded_hal::digital::{InputPin, PinState, ErrorType};
use embedded_hal_async::digital::Wait;
use embassy_time::{Duration, Timer};

pub struct Debouncer<T: Wait + InputPin> {
    input: T,
    debounce_time: Duration,
}

impl<T: Wait + InputPin> Debouncer<T> {
    pub fn new(input: T, debounce_time: Duration) -> Self {
        Self { input, debounce_time }
    }
}

impl<T: Wait + InputPin> ErrorType for Debouncer<T> {
    type Error = T::Error;
}

impl<T: Wait + InputPin> Wait for Debouncer<T> {
    async fn wait_for_high(&mut self) -> Result<(), T::Error> {
        if self.input.is_low()? {
            loop {
                self.input.wait_for_rising_edge().await?;

                Timer::after(self.debounce_time).await;

                if self.input.is_high()? {
                    break;
                }
            }
        }
        Ok(())
    }

    async fn wait_for_low(&mut self) -> Result<(), T::Error> {
        if self.input.is_high()? {
            loop {
                self.input.wait_for_falling_edge().await?;

                Timer::after(self.debounce_time).await;

                if self.input.is_low()? {
                    break;
                }
            }
        }
        Ok(())
    }

    async fn wait_for_rising_edge(&mut self) -> Result<(), T::Error> {
        loop {
            self.input.wait_for_rising_edge().await?;

            Timer::after(self.debounce_time).await;

            if self.input.is_high()? {
                break Ok(());
            }
        }
    }

    async fn wait_for_falling_edge(&mut self) -> Result<(), T::Error> {
        loop {
            self.input.wait_for_falling_edge().await?;

            Timer::after(self.debounce_time).await;

            if self.input.is_low()? {
                break Ok(());
            }
        }
    }

    async fn wait_for_any_edge(&mut self) -> Result<(), T::Error> {
        loop {
            let l1: PinState = self.input.is_high()?.into();

            self.input.wait_for_any_edge().await?;

            Timer::after(self.debounce_time).await;

            let l2: PinState = self.input.is_high()?.into();
            if l1 != l2 {
                break Ok(());
            }
        }
    }

}