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
//! Adds a wrapper for an `InputPin` that debounces it's `is_high()` and `is_low()` methods.

#![cfg_attr(not(test), no_std)]

use core::marker::PhantomData;
use embedded_hal::digital::v2::InputPin;

/// Unit struct for active-low pins.
pub struct ActiveLow;

/// Unit struct for active-high pins.
pub struct ActiveHigh;

/// A debounced input pin.
///
/// Implements approach 1 from [here](http://www.labbookpages.co.uk/electronics/debounce.html#soft)
/// ([archived 2018-09-03](https://web.archive.org/web/20180903142143/http://www.labbookpages.co.uk/electronics/debounce.html#soft)).
///
/// Requires `update()` to be called every ~1ms.
pub struct DebouncedInputPin<T: InputPin, A> {
    /// The wrapped pin.
    pub pin: T,

    /// Whether the pin is active-high or active-low.
    activeness: PhantomData<A>,

    /// The counter.
    counter: i8,

    /// The debounced state.
    state: bool,
}

impl<T: InputPin, A> DebouncedInputPin<T, A> {
    /// Initializes a new debounced input pin.
    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> {
    /// Updates the debounce logic.
    ///
    /// Needs to be called every ~1ms.
    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> {
    /// Updates the debounce logic.
    ///
    /// Needs to be called every ~1ms.
    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;