I was looking for some help on Debouncing on multiple inputs and found this:
Debouncing on Multiple Input Pins
The solution put up by @PerryBebbington was great. I changed a couple lines from his code and made it debounce the state change, not just the press. I'm using this for reading switches.
/* Simple button debounce for 4 buttons. Increments a count and sends the updated count to the serial monitor once per button press */
/* Tested on Mega 2560 */
#define noOfButtons 4 //Exactly what it says; must be the same as the number of elements in buttonPins
#define bounceDelay 40 //Minimum delay before regarding a button as being pressed and debounced
#define minButtonPress 3 //Number of times the button has to be detected as pressed before the press is considered to be valid
const int buttonPins[] = {48, 49, 50, 51}; // Input pins to use, connect buttons between these pins and 0V
uint32_t previousMillis[noOfButtons]; // Timers to time out bounce duration for each button
uint8_t pressCount[noOfButtons]; // Counts the number of times the button is detected as pressed, when this count reaches minButtonPress button is regared as debounced
uint8_t buttonStates[noOfButtons]; //state of buttons, used to see value, and to see if changed
void setup() {
uint8_t i;
uint32_t baudrate = 9600;
Serial.begin(baudrate);
Serial.println("");
Serial.print("Serial port connected: ");
Serial.println(baudrate);
//setup buttonStates Array, populate with HIGH
for (i = 0; i < noOfButtons; ++i) {
buttonStates[i] = HIGH;
}
for (i = 0; i < noOfButtons; ++i) {
pinMode(buttonPins[i], INPUT_PULLUP);
}
}
void loop() {
debounce();
delay(10); //Your other code goes here instead of this delay. DO NOT leave this delay here, it's ONLY for demonstration.
}
void debounce() {
uint8_t i;
uint32_t currentMillis = millis();
for (i = 0; i < noOfButtons; ++i) {
uint8_t thisReading = digitalRead(buttonPins[i]);
if (thisReading == buttonStates[i]) { //Input is unchanged, button not changed or in the middle of bouncing and happens to be back to previous state
previousMillis[i] = currentMillis; //Set previousMillis to millis to reset timeout
pressCount[i] = 0; //Set the number of times the button has been detected as pressed to 0
} else {
if (currentMillis - previousMillis[i] > bounceDelay) {
previousMillis[i] = currentMillis; //Set previousMillis to millis to reset timeout
++pressCount[i];
if (pressCount[i] == minButtonPress) {
buttonStates[i] = thisReading;
doStuff(i); //Button has been debounced. Call function to do whatever you want done.
}
}
}
}
}
// Function to do whatever you want done once the button has been debounced.
// In this example it increments a counter and send the count to the serial monitor.
// Put your own functions here to do whatever you like.
void doStuff(uint8_t buttonNumber) {
Serial.print("Button ");
Serial.print(buttonNumber);
Serial.print(" Current Value: ");
Serial.println(buttonStates[buttonNumber]);
}