Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 13, 2021 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/d6ab8db4eb9636c054aaac301652ff30 to your computer and use it in GitHub Desktop.
Save rust-play/d6ab8db4eb9636c054aaac301652ff30 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
enum IoState {
Low,
High,
Floatit,
}
enum IoPin {
AsOutput(Option<gpioa::PA8<Output<PushPull>>>),
AsInput(Option<gpioa::PA8<Input<Floating>>>),
}
impl IoPin {
fn as_input(&mut self) {
match self {
IoPin::AsOutput(p) => {
let pin = core::mem::replace(p, None).unwrap();
*self = IoPin::AsInput(Some(pin.into_floating_input()));
}
IoPin::AsInput(_) => {}
};
}
fn as_output(&mut self, state: IoState) {
match self {
IoPin::AsOutput(Some(p)) => {pull_pin(p, state)}
IoPin::AsInput(p) => {
let mut pin = core::mem::replace(p, None).unwrap().into_push_pull_output();
pull_pin(&mut pin, state);
*self = IoPin::AsOutput(Some(pin));
}
_ => {}
};
}
fn set_state(&mut self, state: IoState) {
match state {
IoState::Low | IoState::High => self.as_output(state),
IoState::Floatit => self.as_input(),
}
}
}
fn pull_pin(pin: &mut gpioa::PA8<Output<PushPull>>, state: IoState) {
match state {
IoState::Low => {pin.set_low().unwrap()}
IoState::High => {pin.set_high().unwrap()}
IoState::Floatit => {}
}
}
fn main() {
let mut iopin = IoPin::AsInput(Some(gpioa.pa8.into_floating_input()));
iopin.set_state(IoState::Floatit);
iopin.set_state(IoState::Low);
iopin.set_state(IoState::High);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment