From 6081e5a4e0e4c0b4e31654a365efc3e45ba55ec1 Mon Sep 17 00:00:00 2001 From: Tom Armitage Date: Mon, 5 Feb 2024 21:58:19 +0000 Subject: [PATCH] Add support for debouncing non-GPIO inputs. Buttons can be connected via interfaces other than GPIO; for instance, using IO expanders over I2C or SPI, or via multiplexers. This patch adds the option to instantiate a debouncer without a pin specified; it also adds the option to pass an explicit value into `update()`. This means that you could make debouncers for buttons connected via, eg, an I2C expander; every update loop, read the values over I2C, and pass that value into the `update` method for the appropriate object. --- .../PicoDebounceButton/PicoDebounceButton.hpp | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/include/PicoDebounceButton/PicoDebounceButton.hpp b/include/PicoDebounceButton/PicoDebounceButton.hpp index 9b18ee5..2b6101a 100644 --- a/include/PicoDebounceButton/PicoDebounceButton.hpp +++ b/include/PicoDebounceButton/PicoDebounceButton.hpp @@ -36,11 +36,34 @@ class PicoDebounceButton gpio_pull_up(mPin); } + // The constructor can be used without a pin number; + // if so, you will need to manually pass a value to update() + // The default interval is 10ms. + // The default state is PRESSED. + // The default invert is false. + explicit PicoDebounceButton(uint16_t interval = 10, + bool state = PRESSED, + bool invert = false) + : mInterval(interval) + , mState(state) + , mInvert(invert) + { + } + // The update() method should be called in the loop() function. It updates the // button state and returns true if the button state has changed. - auto update() + bool update() + { + return update(gpio_get(mPin)); + } + + // The update() method should be called in the loop() function. + // If no pin is specified, you need to pass the latest state value into + // update() as a parameter. + // It updates the button state and returns true if the button state has changed. + bool update(uint8_t val) { - bool currentState = mInvert ? !gpio_get(mPin) : gpio_get(mPin); + bool currentState = mInvert ? !val : val; uint32_t now = to_ms_since_boot(get_absolute_time()); if (currentState != mLastState) { mLastStateTime = now;