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
93
94
95
96
97
98
99
#![cfg_attr(not(test), no_std)]
use core::marker::PhantomData;
use embedded_hal::digital::v2::InputPin;
pub struct ActiveLow;
pub struct ActiveHigh;
pub struct DebouncedInputPin<T: InputPin, A> {
pub pin: T,
activeness: PhantomData<A>,
counter: i8,
state: bool,
}
impl<T: InputPin, A> DebouncedInputPin<T, A> {
pub fn new(pin: T, _activeness: A) -> Self {
DebouncedInputPin {
pin,
activeness: PhantomData,
counter: 0,
state: false,
}
}
}
impl<T: InputPin, A> InputPin for DebouncedInputPin<T, A> {
type Error = T::Error;
fn is_high(&self) -> Result<bool, Self::Error> {
Ok(self.state)
}
fn is_low(&self) -> Result<bool, Self::Error> {
Ok(!self.state)
}
}
impl<T: InputPin> DebouncedInputPin<T, ActiveHigh> {
pub fn update(&mut self) -> Result<(), <DebouncedInputPin<T, ActiveHigh> as InputPin>::Error> {
if self.pin.is_low()? {
self.counter = 0;
self.state = false;
} else if self.counter < 10 {
self.counter += 1;
}
if self.counter == 10 {
self.state = true;
}
Ok(())
}
}
impl<T: InputPin> DebouncedInputPin<T, ActiveLow> {
pub fn update(&mut self) -> Result<(), <DebouncedInputPin<T, ActiveLow> as InputPin>::Error> {
if self.pin.is_high()? {
self.counter = 0;
self.state = false;
} else if self.counter < 10 {
self.counter += 1;
}
if self.counter == 10 {
self.state = true;
}
Ok(())
}
}
#[cfg(test)]
mod tests;