Expand description

If you can read and write the output state, a pin is toggleable by software.

use embedded_hal::digital::v2::{OutputPin, StatefulOutputPin, ToggleableOutputPin};
use embedded_hal::digital::v2::toggleable;

/// A virtual output pin that exists purely in software
struct MyPin {
    state: bool
}

impl OutputPin for MyPin {
   type Error = void::Void;

   fn set_low(&mut self) -> Result<(), Self::Error> {
       self.state = false;
       Ok(())
   }
   fn set_high(&mut self) -> Result<(), Self::Error> {
       self.state = true;
       Ok(())
   }
}

impl StatefulOutputPin for MyPin {
   fn is_set_low(&self) -> Result<bool, Self::Error> {
       Ok(!self.state)
   }
   fn is_set_high(&self) -> Result<bool, Self::Error> {
       Ok(self.state)
   }
}

/// Opt-in to the software implementation.
impl toggleable::Default for MyPin {}

let mut pin = MyPin { state: false };
pin.toggle().unwrap();
assert!(pin.is_set_high().unwrap());
pin.toggle().unwrap();
assert!(pin.is_set_low().unwrap());

Traits

  • Software-driven toggle() implementation.