use crate::hal::generic::port::{Pin, PinMode, InterruptMode};
use crate::event::{EventSink, OxideEvent};
use core::marker::PhantomData;
#[derive(PartialEq,Eq,Clone,Copy)]
pub enum ButtonState {
Pressed,
Released,
Unknown
}
pub struct Button<P,S>
where
P: 'static + Pin,
S: EventSink
{
pin: &'static mut P,
phantom: PhantomData<S>
}
impl<P,S> Button<P,S>
where
P: Pin,
S: EventSink
{
pub fn using_pin(pin: &'static mut P) -> Self {
pin.set_mode(PinMode::InputFloating);
pin.set_interrupt_mode(InterruptMode::BothEdges);
pin.listen(Some(|source, state|{
S::event(OxideEvent::ButtonEvent(
source,
match state {
true => ButtonState::Pressed,
false => ButtonState::Released
}));
}));
Button {
pin,
phantom: PhantomData::default()
}
}
pub fn pullup(self, enable: bool) -> Self {
match enable {
true => self.pin.set_mode(PinMode::InputPullup),
false => self.pin.set_mode(PinMode::InputFloating)
}
self
}
pub fn is_pressed(&self) -> bool {
!self.pin.get()
}
pub fn state(&self) -> ButtonState {
match self.pin.get() {
true => ButtonState::Pressed,
false => ButtonState::Released
}
}
}