|
| 1 | +use core::ops; |
| 2 | + |
| 3 | +/// Newtype around [`gpio_cdev::LineHandle`] that implements the `embedded-hal` traits |
| 4 | +/// |
| 5 | +/// [`gpio_cdev::LineHandle`]: https://docs.rs/gpio-cdev/0.2.0/gpio_cdev/struct.LineHandle.html |
| 6 | +pub struct CdevPin(pub gpio_cdev::LineHandle, bool); |
| 7 | + |
| 8 | +impl CdevPin { |
| 9 | + /// See [`gpio_cdev::Line::request`][0] for details. |
| 10 | + /// |
| 11 | + /// [0]: https://docs.rs/gpio-cdev/0.2.0/gpio_cdev/struct.Line.html#method.request |
| 12 | + pub fn new(handle: gpio_cdev::LineHandle) -> Result<Self, gpio_cdev::errors::Error> { |
| 13 | + let info = handle.line().info()?; |
| 14 | + Ok(CdevPin(handle, info.is_active_low())) |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +impl hal::digital::v2::OutputPin for CdevPin { |
| 19 | + type Error = gpio_cdev::errors::Error; |
| 20 | + |
| 21 | + fn set_low(&mut self) -> Result<(), Self::Error> { |
| 22 | + self.0.set_value(0) |
| 23 | + } |
| 24 | + |
| 25 | + fn set_high(&mut self) -> Result<(), Self::Error> { |
| 26 | + self.0.set_value(1) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +impl hal::digital::v2::InputPin for CdevPin { |
| 31 | + type Error = gpio_cdev::errors::Error; |
| 32 | + |
| 33 | + fn is_high(&self) -> Result<bool, Self::Error> { |
| 34 | + if !self.1 { |
| 35 | + self.0.get_value().map(|val| val != 0) |
| 36 | + } else { |
| 37 | + self.0.get_value().map(|val| val == 0) |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + fn is_low(&self) -> Result<bool, Self::Error> { |
| 42 | + self.is_high().map(|val| !val) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +impl ops::Deref for CdevPin { |
| 47 | + type Target = gpio_cdev::LineHandle; |
| 48 | + |
| 49 | + fn deref(&self) -> &Self::Target { |
| 50 | + &self.0 |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +impl ops::DerefMut for CdevPin { |
| 55 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 56 | + &mut self.0 |
| 57 | + } |
| 58 | +} |
0 commit comments