inverted_pin/
inverted.rs

1use embedded_hal::digital::{Error, ErrorType, InputPin, OutputPin, StatefulOutputPin};
2
3/// Inverted input/output pin
4///
5/// If wrapping an output pin, whenever setting this pin to a high or low level,
6/// the wrapped pin will be set to the opposite level.
7///
8/// Likewise, if wrapping an input pin, whenever reading this pin it will read
9/// the wrapped input pin and return the opposite level.
10#[derive(Debug, Clone, Copy)]
11pub struct InvertedPin<P> {
12    pin: P,
13}
14
15impl<P> InvertedPin<P> {
16    /// Create new instance
17    pub fn new(pin: P) -> Self {
18        Self { pin }
19    }
20
21    /// Destroy instance and return the wrapped pin
22    pub fn destroy(self) -> P {
23        self.pin
24    }
25}
26
27impl<P, E> ErrorType for InvertedPin<P>
28where
29    P: ErrorType<Error = E>,
30    E: Error,
31{
32    type Error = E;
33}
34
35impl<P, E> OutputPin for InvertedPin<P>
36where
37    P: OutputPin<Error = E>,
38    E: Error,
39{
40    fn set_high(&mut self) -> Result<(), Self::Error> {
41        self.pin.set_low()
42    }
43
44    fn set_low(&mut self) -> Result<(), Self::Error> {
45        self.pin.set_high()
46    }
47}
48
49impl<P, E> InputPin for InvertedPin<P>
50where
51    P: InputPin<Error = E>,
52    E: Error,
53{
54    fn is_high(&mut self) -> Result<bool, Self::Error> {
55        self.pin.is_low()
56    }
57
58    fn is_low(&mut self) -> Result<bool, Self::Error> {
59        self.pin.is_high()
60    }
61}
62
63impl<P, E> StatefulOutputPin for InvertedPin<P>
64where
65    P: StatefulOutputPin<Error = E>,
66    E: Error,
67{
68    fn is_set_high(&mut self) -> Result<bool, Self::Error> {
69        self.pin.is_set_low()
70    }
71
72    fn is_set_low(&mut self) -> Result<bool, Self::Error> {
73        self.pin.is_set_high()
74    }
75}