/*
debounce - one of five
https://forum.arduino.cc/t/having-trouble-implementing-debounce-into-my-code/1119513/10
2023-04-26 by noiasca
sketch in forum
*/
// a simple button class
class Button { // class to debounce switches
const uint8_t buttonPin; // the pin for the button
static constexpr uint16_t debounceDelay = 20; // the debounce time - one value for all buttons (hence "static")
const bool active; // is the button HIGH or LOW active
bool lastButtonState = HIGH; // previous state of pin
uint32_t lastDebounceTime = 0; // previous debounce time (we just need short debounce delay, so the rollover of the byte variable works fine and spares 3 bytes compared to an unsigned long)
public:
Button(uint8_t attachTo, bool active = LOW) : buttonPin(attachTo), active(active) {}
void begin() { // sets the pinMode and optionally activates the internal pullups
if (active == LOW)
pinMode(buttonPin, INPUT_PULLUP);
else
pinMode(buttonPin, INPUT);
}
bool wasPressed() {
bool buttonState = LOW;
byte reading = LOW;
if (digitalRead(buttonPin) == active) reading = HIGH;
if (((millis()) - lastDebounceTime) > debounceDelay) {
if (reading != lastButtonState && lastButtonState == LOW) {
buttonState = HIGH;
}
lastDebounceTime = millis(); // we store just the last byte from millis()
lastButtonState = reading;
}
return buttonState;
}
};
Button button[] {2, 3, 4, 5, 6}; // create button object on these pins, by default, activate internal pullups
const uint8_t outputPin[] {7, 8, 9, 10, 11}; // pins for outputs
const size_t noOfPins = sizeof(outputPin); // calculate how many pins are used
int currentLed = -1; // active LED, -1 if none
void setup() {
for (int i = 0; i < noOfPins; i++) { // for each button/pin ...
button[i].begin(); // call begin
pinMode(outputPin[i], OUTPUT); // set LED pins to output
}
}
void loop() {
for (int i = 0; i < noOfPins; i++) {
if (button[i].wasPressed()) {
if (currentLed == i) {
digitalWrite(outputPin[currentLed], LOW); // switch off LED
currentLed = -1; // mark as no active LED
}
else {
digitalWrite(outputPin[currentLed], LOW); // switch off old LED
currentLed = i; // remember new LED
digitalWrite(outputPin[currentLed], HIGH); // switch on new LED
}
}
}
}