/*
Debounce Buttons OOP
a simple class to check if a button was pressed
debounce without delay, non blocking, and reuseable
*/
//-------------------------------------------------------------------------------------------------------------------------- Taster Klasse (Kassenautomat) --------------------------------------------------------------------------------------------------------------------
class Button { // class to debounce switches
const byte buttonPin; // the pin for the button
static constexpr byte 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
byte 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(byte 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() & 0xFF ) - lastDebounceTime) > debounceDelay) {
if (reading != lastButtonState && lastButtonState == LOW) {
buttonState = HIGH;
}
lastDebounceTime = millis() & 0xFF; // we store just the last byte from millis()
lastButtonState = reading;
}
return buttonState;
}
};
Button buttonA(A5); // create a button object on this pin, by default, activate internal pullups
Button buttonB(A6);
Button buttonC(A7);
void setup() {
Serial.begin(115200);
Serial.println(F("Start"));
buttonA.begin(); // start button
buttonB.begin();
buttonC.begin();
Serial.println(F("end of setup"));
}
void loop() {
if (buttonA.wasPressed())
Serial.println(F("buttonA was pressed"));
if (buttonB.wasPressed())
Serial.println(F("buttonB was pressed"));
if (buttonC.wasPressed())
Serial.println(F("buttonC was pressed"));
}