Skip to content

Add try_set_state method for OutputPin #239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Added
- 10-bit addressing mode for I2C traits.
- `try_set_state` method for `OutputPin` using an input `PinState` value.

### Changed

Expand Down
51 changes: 51 additions & 0 deletions src/digital.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,45 @@
//! Digital I/O

use core::{convert::From, ops::Not};

/// Digital output pin state
///
/// Conversion from `bool` and logical negation are also implemented
/// for this type.
/// ```rust
/// # use embedded_hal::digital::PinState;
/// let state = PinState::from(false);
/// assert_eq!(state, PinState::Low);
/// assert_eq!(!state, PinState::High);
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum PinState {
/// Low pin state
Low,
/// High pin state
High,
}

impl From<bool> for PinState {
fn from(value: bool) -> Self {
match value {
false => PinState::Low,
true => PinState::High,
}
}
}

impl Not for PinState {
type Output = PinState;

fn not(self) -> Self::Output {
match self {
PinState::High => PinState::Low,
PinState::Low => PinState::High,
}
}
}

/// Single digital push-pull output pin
pub trait OutputPin {
/// Error type
Expand All @@ -16,6 +56,17 @@ pub trait OutputPin {
/// *NOTE* the actual electrical state of the pin may not actually be high, e.g. due to external
/// electrical sources
fn try_set_high(&mut self) -> Result<(), Self::Error>;

/// Drives the pin high or low depending on the provided value
///
/// *NOTE* the actual electrical state of the pin may not actually be high or low, e.g. due to external
/// electrical sources
fn try_set_state(&mut self, state: PinState) -> Result<(), Self::Error> {
match state {
PinState::Low => self.try_set_low(),
PinState::High => self.try_set_high(),
}
}
}

/// Push-pull output pin that can read its output state
Expand Down