From abcef1dd3e710ac6c8f107ff9da4dc822e6b166e Mon Sep 17 00:00:00 2001 From: Tom Igoe Date: Fri, 3 Jul 2009 22:26:41 +0000 Subject: [PATCH] Improvements in debounce from Limor --- .../examples/Digital/Debounce/Debounce.pde | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/build/shared/dist/examples/Digital/Debounce/Debounce.pde b/build/shared/dist/examples/Digital/Debounce/Debounce.pde index f493ddb85..162289fa7 100644 --- a/build/shared/dist/examples/Digital/Debounce/Debounce.pde +++ b/build/shared/dist/examples/Digital/Debounce/Debounce.pde @@ -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: - lastDebounceTime = millis(); + + // If the switch changed, due to noise or pressing: + if (reading != lastButtonState) { + // reset the debouncing timer + lastDebounceTime = millis(); + } + + 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; } + + // set the LED using the state of the button: + digitalWrite(ledPin, buttonState); - // set the LED using the ledState variable: - digitalWrite(ledPin, ledState); - - // save the buttonState. Next time through the loop, + // save the reading. Next time through the loop, // it'll be the lastButtonState: - lastButtonState = buttonState; -} + lastButtonState = reading; +} \ No newline at end of file