// button debouncer
byte buttonPin = 12; // DIO pin for button N.O. pin
int buttonCount; // count button presses
unsigned long buttonTimer, buttonTimeout = 50; // used in readButton() debounce timer
bool currentButtonState, lastButtonRead; // record button states
void setup() {
Serial.begin(115200);
pinMode(buttonPin, INPUT_PULLUP); // pin --> button (n.o.) button --> gnd
Serial.print("Press yer button on Pin ");
Serial.print(buttonPin);
Serial.print(".\nButton count: ");
Serial.print(buttonCount);
}
void loop() {
debounceButton();
}
void debounceButton() {
bool currentButtonRead = digitalRead(buttonPin); // read button pin
if (currentButtonRead != lastButtonRead) { // if THIS read is not the same as LAST read...
buttonTimer = millis(); // ...start a timer by storing millis()
lastButtonRead = currentButtonRead; // ... and store current state
}
if ((millis() - buttonTimer) > buttonTimeout) { // if button change was longer than debounce timeout (NOT NOISE)
if (currentButtonState == HIGH && lastButtonRead == LOW) { // ... and State is "NOT pressed" while Button "IS PRESSED"
//================================================== // The button WAS pressed...
digitalWrite(LED_BUILTIN, HIGH); // Do something here...
Serial.print(++buttonCount); // ... an action...
digitalWrite(LED_BUILTIN, LOW); // ... or call functions
//==================================================
}
currentButtonState = currentButtonRead; // update button state for first if() condition test
}
}