I need to debounce 8 switches for a puzzle game I'm writing. I tried a test program without debouncing and the switch results are bad and/or unpredictable. The code below acts as expected with the button pushed - solid ZERO. With the normally open button released, results seem random. I get hundreds of 1's with an occasional zero or groups of alternating 1's and 0's, usually from 5 to ten of each before reversing.
While I'm waiting to hear, I'll go work on two other sets of code I got from online or the Arduino site and see what they do.
/* Debounce */
/* PROBLEM with this code:
(No delay in the serial printing, so I get readings as fast as the
processor can read and display them.)
Button pressed = all zeros (Normal and as expected)
Button released = Seemingly random patterns. Sometimes hundreds of 1's
with occasional zeros, sometimes oscillating back and forth with
5 to 10 ones, then 5 to ten zeros. */
const int buttonPin = 22; // the number of the pushbutton pin on the Arduino Mega
const int ledPin = 6; // the number of the LED pin on the Arduino Mega
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 50; // the debounce time; increase if the output flickers
int count=0;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop()
{
int reading = digitalRead(buttonPin);
//Serial.print(" Reading: ");
Serial.print(reading, DEC);
count++;
if (count>50)
{ // Every 50 bits printed, insert a carriage return
count=0;
Serial.println(" ");
}
if (reading != lastButtonState) // Has button changed since last reading?
lastDebounceTime = millis();
if ((millis() - lastDebounceTime) > debounceDelay)
buttonState = reading;
digitalWrite(ledPin, buttonState);
lastButtonState = reading;
}