/*
Forum: https://forum.arduino.cc/t/need-beginner-help-with-debounce-logic/1425853
Wokwi: https://wokwi.com/projects/453763608403049473
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.
2026/01/21
A counter has been added that is incremented and decremented by pressing the two
buttons. To further speed up the process, the increment and decrement values are
calculated based on the position of a slide potentiometer
slide close to the bottom (next to the VCC pin) -> 1
slide between bottom and top position -> a value out of 10, 100, 1000, 10000
slide close to the top position (next to the GND pin) -> plus/minus 100000
The counter value is adjusted in accordance to the increment/decrement:
counter is rounded off by the inc/dec value, e.g.
counter increment calculation new counter
12345 100 (12345/100)*100 12300
12399 100 (12399/100)*100 12300
12345 1000 (12345/1000)*1000 12000
12399 1000 (12999/1000)*1000 12000
-12345 1000 (-12345/1000)*1000 -12000
-12399 1000 (-12999/1000)*1000 -12000
This makes it easier for a human observer to follow the count up/down.
*/
#include "accelbtn.h"
constexpr byte buttonPin[] {2, 3};
constexpr int buttons = sizeof(buttonPin) / sizeof(buttonPin[0]);
AccelBtnClass button[buttons];
long counter = 0;
long increment;
long decrement;
void setup() {
Serial.begin(115200);
for (int i = 0; i < buttons; i++) {
// Pin No, minInterval, maxInterval, decrement
button[i].init(buttonPin[i], 50, 300, 50);
}
}
void loop() {
readDeltaValue();
doSomething();
}
void readDeltaValue() {
uint16_t analogValue = analogRead(A0);
uint16_t range = map(analogValue, 0, 1024, 0, 6);
long deltaValue = 1;
for (int i = 0; i < range; i++) {
deltaValue *= 10;
}
increment = deltaValue;
decrement = deltaValue;
}
void doSomething() {
if (button[0].down()) {
adjustCounterTo(increment);
counter += increment;
Serial.print(button[0].getDownInterval());
Serial.print("\t\t");
Serial.print(counter);
Serial.print("\t\t");
Serial.println(increment);
}
if (button[1].down()) {
adjustCounterTo(decrement);
counter -= decrement;
Serial.print(button[1].getDownInterval());
Serial.print("\t\t");
Serial.print(counter);
Serial.print("\t\t");
Serial.println(decrement);
}
}
void adjustCounterTo(long delta) {
counter = (counter / delta) * delta;
}