shared_pin/
lib.rs

1//! An abstraction of the embedded_hal::digital::v2 OutputPin and InputPin
2//! to be shared between functions using an Rc<RefCell<Pin>>
3#![no_std]
4#![allow(dead_code)]
5#![deny(missing_docs)]
6#![deny(warnings)]
7
8extern crate alloc;
9
10use alloc::rc::Rc;
11use core::cell::RefCell;
12
13use embedded_hal::digital::v2::{InputPin, OutputPin};
14
15/// SharedPin struct containing the Rc<RefCell<Pin>>
16pub struct SharedPin<Pin> {
17    pin: Rc<RefCell<Pin>>,
18}
19
20impl<Pin> SharedPin<Pin>
21{
22    /// Create a new SharedPin instance by supplying a pin.
23    pub fn new(pin: Pin) -> Self {
24        Self {
25            pin: Rc::new(RefCell::new(pin)),
26        }
27    }
28}
29
30/// Clone implementation using Rc::clone()
31impl<Pin> Clone for SharedPin<Pin> {
32    fn clone(&self) -> Self {
33        Self {
34            pin: Rc::clone(&self.pin),
35        }
36    }
37}
38
39
40impl<Pin> OutputPin for SharedPin<Pin>
41    where
42        Pin: OutputPin,
43{
44    type Error = ();
45
46    /// Borrows the RefCell and calls set_low() on the pin
47    fn set_low(&mut self) -> Result<(), Self::Error> {
48        self.pin.borrow_mut().set_low().map_err(|_e| ())
49    }
50
51    /// Borrows the RefCell and calls set_high() on the pin
52    fn set_high(&mut self) -> Result<(), Self::Error> {
53        self.pin.borrow_mut().set_high().map_err(|_e| ())
54    }
55}
56
57impl<Pin> InputPin for SharedPin<Pin>
58    where
59        Pin: InputPin,
60{
61    type Error = ();
62
63    /// Borrows the RefCell and calls is_high() on the pin
64    fn is_high(&self) -> Result<bool, Self::Error> {
65        self.pin.borrow_mut().is_high().map_err(|_e| ())
66    }
67
68    /// Borrows the RefCell and calls is_low() on the pin
69    fn is_low(&self) -> Result<bool, Self::Error> {
70        self.pin.borrow_mut().is_low().map_err(|_e| ())
71    }
72}