/*
Forum: https://forum.arduino.cc/t/need-beginner-help-with-debounce-logic/1425853
Wokwi: https://wokwi.com/projects/453484771264915457
ec2021
Example for reading buttons with "acceleration" of returned
(btn.down() == True)
AccelBtnClass provides the ability to set a minimum and maximum interval
to receive true from the function btn.down() while the button is pressed.
The time to return true is decremented by a given value "decrement" in btn.init(...).
Once the button has been released the interval is reset to maxInterval
again.
*/
constexpr byte buttonPin[] {2, 3};
constexpr int buttons = sizeof(buttonPin) / sizeof(buttonPin[0]);
class AccelBtnClass {
private:
byte pin;
byte state;
byte lastState;
unsigned long lastChange;
unsigned long lastPressTime;
unsigned long lastCheckTime;
unsigned long accelInterval;
unsigned long minInterval;
unsigned long maxInterval;
unsigned long decrement;
public:
init(byte p, unsigned long minIntv, unsigned long maxIntv, unsigned long decr) {
pin = p;
pinMode(pin, INPUT_PULLUP);
lastPressTime = 0;
lastCheckTime = 0;
minInterval = min(minIntv, maxIntv);
maxInterval = max(minIntv, maxIntv);
accelInterval = maxInterval;
decrement = decr;
}
unsigned long getLastPressTime() {
return lastPressTime;
};
unsigned long getLastCheckTime() {
return lastCheckTime;
};
void reset() {
lastPressTime = 0;
}
boolean pressed() {
byte actState = digitalRead(pin);
if (actState != lastState) {
lastChange = millis();
lastState = actState;
};
if (actState != state && millis() - lastChange > 30) {
state = actState;
if (!state) lastPressTime = lastChange;
return !state;
}
return false;
}
boolean down() {
if (!digitalRead(pin)) {
if (millis() - lastCheckTime >= accelInterval) {
lastCheckTime = millis();
if (accelInterval >= minInterval + decrement) {
accelInterval -= decrement;
}
return true;
} else {
return false;
}
} else {
accelInterval = maxInterval;
return false;
}
}
};
AccelBtnClass button[buttons];
void setup() {
Serial.begin(115200);
for (int i = 0; i < buttons; i++) {
// Pin No, minInterval, maxInterval, decrement
button[i].init(buttonPin[i], 30, 330, 50);
}
}
void loop() {
doSomething();
}
void doSomething() {
for (int i = 0; i < buttons; i++) {
if (button[i].down()) {
Serial.print("Button ");
Serial.print(i);
Serial.print(" down @ ");
Serial.println(button[i].getLastCheckTime());
}
}
}