byte button2pin = 2, button3pin = 3; // configure button pins
unsigned long button3counter, button2counter; // configure button-press counters
unsigned long timer, timeout = 50; // used in readButton2()
bool currentButtonState, lastButtonRead; // used in readButton2()
void setup() {
Serial.begin(115200);
pinMode(button2pin, INPUT_PULLUP); // pin to button (n.o.) button to gnd
pinMode(button3pin, INPUT_PULLUP);
Serial.println("Press button 3 for \"IS BEING\" pressed.\nPress button 2 for \"WAS\" pressed.");
}
void loop() {
readButton2(); // read the "was pressed" button in a stand-alone function
readButton3(); // read "is pressed" button
}
void readButton2() {
bool currentButtonRead = digitalRead(button2pin); // read button pin
if (currentButtonRead != lastButtonRead) { // if button pin changes...
timer = millis(); // ...start a timer
lastButtonRead = currentButtonRead; // ... and store current state
}
if ((millis() - timer) > timeout) { // if button change was longer than debounce timeout
if (currentButtonState == HIGH && lastButtonRead == LOW) { // ... and State is "NOT pressed" while Button "IS PRESSED"
//==================================================
digitalWrite(LED_BUILTIN, HIGH); // The button was pressed...
showButton(button2pin, ++button2counter);; // Put actions or function calls here
digitalWrite(LED_BUILTIN, LOW);
//==================================================
}
currentButtonState = currentButtonRead; // update button state
}
}
void readButton3() {
if (!digitalRead(button3pin)) { // button is pressed
digitalWrite(LED_BUILTIN, HIGH); // LED on
showButton(button3pin, ++button3counter); // increase button count and print
}
else(digitalWrite(LED_BUILTIN, LOW)); // LED off
}
void showButton(byte button, unsigned long count) {
Serial.print("Button ");
Serial.print(button); // print button pin
Serial.print(button == 3 ? " IS " : " WAS"); // if "3" print "IS", else print "WAS"
Serial.print(" pressed ");
Serial.print(count); // print button press count
if (count > 1)
Serial.println(" times.");
else
Serial.println(" time.");
}
Button 3
without debounce
showing 'IS' pressed
Button 2
with debounce
showing 'WAS' pressed