// Debounc validates a button press only when longer than the debounce timeout.
byte buttonpin[] = { 2, 3, 4 }; // declare button pins in an array
byte element; // indicates pressed button/pin
byte arraySize = sizeof(buttonpin) / sizeof(buttonpin[0]); // get number of elements in button array
unsigned long timer; // timer keeps track of length of button press (or noise/ringing).
unsigned long timeout = 100; // timeout (in milliseconds) is the minimum for "a button is pressed".
void setup() {
Serial.begin(115200); // start serial monitor
for (int i = 0; i < arraySize; i++) // count to number of elements in button array
pinMode(buttonpin[i], INPUT_PULLUP); // configure button pins for reading (LOW when pressed)
}
void loop() {
if (element > arraySize) // count through array... do not use for() loops. they blocking program flow.
element = 0; // if beyond the array size, start again from the first element
if (!digitalRead(buttonpin[element])) { // button may have been pressed, or just noise/ringing
if (millis() - timer > timeout) { // measure time from last "press" to this "press. replaces delay();
if (digitalRead(buttonpin[element])) { // valid button was released after debounce timeout
timer = millis(); // reset timer after valid button press
myFunction(element); // call the function associated with the button press
}
}
}
element++; // check next array element
}
void myFunction(int i) {
Serial.print(buttonpin[i]); // print the pin number
}