Improve button press logic

This commit is contained in:
hodasemi 2022-07-23 14:52:05 +02:00
parent ceb5423420
commit 857840e3bf
2 changed files with 9 additions and 10 deletions

View file

@ -12,7 +12,7 @@ pub const BUTTON_COUNT: usize = 8;
pub struct Button { pub struct Button {
pub index: usize, pub index: usize,
pub pin: Pin<Input<PullUp>, Dynamic>, pub pin: Pin<Input<PullUp>, Dynamic>,
pub is_low: bool, pub was_low: bool,
// pub last_debounce_time: u64, // pub last_debounce_time: u64,
} }
@ -20,8 +20,8 @@ impl Button {
pub fn new(index: usize, pin: Pin<Input<PullUp>, Dynamic>) -> Self { pub fn new(index: usize, pin: Pin<Input<PullUp>, Dynamic>) -> Self {
Button { Button {
index, index,
was_low: pin.is_low(),
pin, pin,
is_low: true,
// last_debounce_time: 0, // last_debounce_time: 0,
} }
} }
@ -30,14 +30,13 @@ impl Button {
where where
F: FnMut(usize, bool), F: FnMut(usize, bool),
{ {
match (self.pin.is_high(), self.is_low) { // check if current state is different from previous one
(true, true) | (false, false) => { if self.pin.is_high() == self.was_low {
self.is_low = !self.is_low; // change state
self.was_low = !self.was_low;
f(self.index, !self.is_low); //
} f(self.index, !self.was_low);
_ => (),
} }
} }
} }

View file

@ -55,7 +55,7 @@ fn main() -> ! {
loop { loop {
for button in buttons.iter_mut() { for button in buttons.iter_mut() {
button.check_state(|index, pressed| { button.check_state(|index, pressed| {
if !pressed { if pressed {
ufmt::uwriteln!(&mut serial, "{}{}{}", MESSAGE_START, index, MESSAGE_END) ufmt::uwriteln!(&mut serial, "{}{}{}", MESSAGE_START, index, MESSAGE_END)
.unwrap(); .unwrap();
} }