From b7da415d6f1376c2a3b0118bc59eb6911503e1e6 Mon Sep 17 00:00:00 2001 From: Mike Date: Fri, 28 Dec 2012 20:16:42 +0000 Subject: [PATCH] Fix Debounce example to work as described This alters the debounce example code to toggle the LED rather than just use the button state to set the LED state. Fixes #293 --- .../examples/02.Digital/Debounce/Debounce.ino | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/build/shared/examples/02.Digital/Debounce/Debounce.ino b/build/shared/examples/02.Digital/Debounce/Debounce.ino index 89416b269..3ead18503 100644 --- a/build/shared/examples/02.Digital/Debounce/Debounce.ino +++ b/build/shared/examples/02.Digital/Debounce/Debounce.ino @@ -19,6 +19,8 @@ by David A. Mellis modified 30 Aug 2011 by Limor Fried + modified 28 Dec 2012 + by Mike Walters This example code is in the public domain. @@ -43,6 +45,9 @@ long debounceDelay = 50; // the debounce time; increase if the output flicker void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); + + // set initial LED state + digitalWrite(ledPin, ledState); } void loop() { @@ -62,12 +67,21 @@ void loop() { 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; + + // if the button state has changed: + if (reading != buttonState) { + buttonState = reading; + + // only toggle the LED if the new button state is HIGH + if (buttonState == HIGH) { + ledState = !ledState; + + // set the LED: + digitalWrite(ledPin, ledState); + } + } } - // 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 = reading;