From 857840e3bff6119ff98d910120e93e0abc6e3be3 Mon Sep 17 00:00:00 2001 From: hodasemi Date: Sat, 23 Jul 2022 14:52:05 +0200 Subject: [PATCH] Improve button press logic --- arduino/src/buttons.rs | 17 ++++++++--------- arduino/src/main.rs | 2 +- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/arduino/src/buttons.rs b/arduino/src/buttons.rs index 6532077..0057352 100644 --- a/arduino/src/buttons.rs +++ b/arduino/src/buttons.rs @@ -12,7 +12,7 @@ pub const BUTTON_COUNT: usize = 8; pub struct Button { pub index: usize, pub pin: Pin, Dynamic>, - pub is_low: bool, + pub was_low: bool, // pub last_debounce_time: u64, } @@ -20,8 +20,8 @@ impl Button { pub fn new(index: usize, pin: Pin, Dynamic>) -> Self { Button { index, + was_low: pin.is_low(), pin, - is_low: true, // last_debounce_time: 0, } } @@ -30,14 +30,13 @@ impl Button { where F: FnMut(usize, bool), { - match (self.pin.is_high(), self.is_low) { - (true, true) | (false, false) => { - self.is_low = !self.is_low; + // check if current state is different from previous one + if self.pin.is_high() == self.was_low { + // change state + self.was_low = !self.was_low; - f(self.index, !self.is_low); - } - - _ => (), + // + f(self.index, !self.was_low); } } } diff --git a/arduino/src/main.rs b/arduino/src/main.rs index 267442a..0e2d7b0 100644 --- a/arduino/src/main.rs +++ b/arduino/src/main.rs @@ -55,7 +55,7 @@ fn main() -> ! { loop { for button in buttons.iter_mut() { button.check_state(|index, pressed| { - if !pressed { + if pressed { ufmt::uwriteln!(&mut serial, "{}{}{}", MESSAGE_START, index, MESSAGE_END) .unwrap(); }