Improvements in debounce from Limor

This commit is contained in:
Tom Igoe 2009-07-03 22:26:41 +00:00
parent 6fef0130f4
commit abcef1dd3e
1 changed files with 23 additions and 23 deletions

View File

@ -17,8 +17,8 @@
created 21 November 2006
by David A. Mellis
modified 17 Jun 2009
by Tom Igoe
modified 3 Jul 2009
by Limor Fried
http://www.arduino.cc/en/Tutorial/Debounce
@ -34,10 +34,10 @@ 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
// the follow variables are long's because the time, measured in miliseconds,
// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 200; // the debounce time, increase if the output flickers
long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
pinMode(buttonPin, INPUT);
@ -45,29 +45,29 @@ void setup() {
}
void loop() {
buttonState = digitalRead(buttonPin);
// read the state of the switch into a local variable:
int reading = digitalRead(buttonPin);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited
// long enough since the last press to ignore any noise:
if ((buttonState == HIGH) &&
(lastButtonState == LOW) &&
(millis() - lastDebounceTime) > debounceDelay) {
// toggle the output
if (ledState == HIGH) {
ledState = LOW;
} else {
ledState = HIGH;
}
// ... and store the time of the last button press
// in a variable:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
// set the LED using the ledState variable:
digitalWrite(ledPin, ledState);
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
buttonState = reading;
}
// save the buttonState. Next time through the loop,
// set the LED using the state of the button:
digitalWrite(ledPin, buttonState);
// save the reading. Next time through the loop,
// it'll be the lastButtonState:
lastButtonState = buttonState;
lastButtonState = reading;
}