Hey guys.
In order to simplify my debouncing of buttons in my Arduino projects,
I've been writing this code:
const byte buttonA = 5; // arduino pin 5
const byte buttonB = 10; // arduino pin 10
const byte buttonC = 6; // arduino pin 6
// - Arduino DIO pin states -
// current state of the button:
byte buttonState[13]=
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// last state of the button:
byte lastButtonState[13] =
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
unsigned long lastDebounceTime = 0;
// keeps track of the last time we checked button state.
// *** adjustable ***
const int debounceDelay = 20;
// how long to wait on button state before confirmation.
// if this variable is too long, then quick taps of the button
// may not register. Too short, and button bouncing
// could register as false button press/release.
void setup() {
// set up the buttons as inputs:
pinMode(buttonA, INPUT);
pinMode(buttonB, INPUT);
pinMode(buttonC, INPUT);
} // end of setup()
void loop() {
// constantly check for button push:
if(buttonEdgeDetectLow(buttonA)) {
// do something now that buttonA was pressed
}
if(buttonEdgeDetectLow(buttonB)) {
// do something now that buttonB was pressed
}
if(buttonEdgeDetectLow(buttonC)) {
// do something now that buttonC was pressed
}
} // end of loop()
// FUNCTION:
boolean buttonEdgeDetectLow(byte button)
{
// check if the button has been pressed:
byte reading = digitalRead(button);
if(reading != lastButtonState[button])
{
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay)
{
if(reading != buttonState[button])
{
buttonState[button] = reading;
if(buttonState[button] == LOW)
{
return true;
}
}
return false;
}
// set last button state = to reading.
lastButtonState[button] = reading;
} // end of buttonEdgeDetectLow()
It works great for when you are using any DIO pins 0-13 as a button.
But unfortunately my most recent project uses pins A0, A1, and A2 as buttons. (using analog pins as a digital input pin).
So my question to you guys is:
How can I modify my code to allow me to debounce Analog pins? (and not just the stock digital pins 0-13)
p.s. You will notice that use of my code above means creating an array of potentially wasted-bytes that will never be used. (in the example above: an array of 13 bytes is used even though I only ever access 3). Generally this wasted memory isn't an issue for my projects, but I'd also appreciate it if someone could explain a more efficient, yet just as simple way to implement my debounce method.
Thanks.
-Josh!