Arduino: Better debounce routine

Hello,

This is an Arduino routine to check if a button is pressed using the Arduino SDK.

Key features:

  • Implements debouncing to avoid false positives.
  • Completely non-blocking, no delay() function calls.
  • Works with multiple buttons, just add them to the array

This code detects when a button is pressed and then released with a sufficient degree of reliability, it can be used when it’s important for the code in loop() to keep running.

true is returned when a button press and subsequent release is detected. / false otherwise

Main loop code:

void loop() {

if (isButtonPressed(WIFI_B_PIN)) {

//Action 1…

}

if (isButtonPressed(BUTTON_PIN)) {

//Action 2…

}

}

Routine:

#define NHB 2
unsigned long lastDebounceTime[NHB] = {0, 0};
int lastButtonState[NHB] = {HIGH, HIGH};
bool buttonStep[NHB] = {false, false};
uint8_t buttonsArray[NHB] = {BUTTON_PIN, WIFI_B_PIN};

//BUTTON -> Array pos
int buttonToPos(uint8_t BUTTON) {
for (int i=0; i<NHB; i++) {
if (buttonsArray[i] == BUTTON) {
return i;
}
}

return -1; //Not found
}

bool isButtonPressed(uint8_t BUTTON) {

int value = digitalRead(BUTTON);
int pos = buttonToPos(BUTTON);

//Start counting when button is first pressed
if (value != lastButtonState[pos]) {
lastDebounceTime[pos] = millis();
}

//Set current state
lastButtonState[pos] = value;

//If true, at least SHORT_PRESS_BOUNCE ms have passed since the button was first pressed
if ((millis() – lastDebounceTime[pos]) > SHORT_PRESS_BOUNCE) {

if (value == lastButtonState[pos] && value == LOW) {
buttonStep[pos] = true;
} else if (value == lastButtonState[pos] && value == HIGH) {
if (buttonStep[pos]==true) {
buttonStep[pos] = false;
return true;
}
}

}

return false;
}

 

%d bloggers like this: