Skip to content

Commit 5c9ab23

Browse files
committed
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 arduino#293
1 parent 9f727ac commit 5c9ab23

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

build/shared/examples/02.Digital/Debounce/Debounce.ino

+18-4
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
by David A. Mellis
2020
modified 30 Aug 2011
2121
by Limor Fried
22+
modified 28 Dec 2012
23+
by Mike Walters
2224
2325
This example code is in the public domain.
2426
@@ -43,6 +45,9 @@ long debounceDelay = 50; // the debounce time; increase if the output flicker
4345
void setup() {
4446
pinMode(buttonPin, INPUT);
4547
pinMode(ledPin, OUTPUT);
48+
49+
// set initial LED state
50+
digitalWrite(ledPin, ledState);
4651
}
4752

4853
void loop() {
@@ -62,12 +67,21 @@ void loop() {
6267
if ((millis() - lastDebounceTime) > debounceDelay) {
6368
// whatever the reading is at, it's been there for longer
6469
// than the debounce delay, so take it as the actual current state:
65-
buttonState = reading;
70+
71+
// if the button state has changed:
72+
if (reading != buttonState) {
73+
buttonState = reading;
74+
75+
// only toggle the LED if the new button state is HIGH
76+
if (buttonState == HIGH) {
77+
ledState = !ledState;
78+
79+
// set the LED:
80+
digitalWrite(ledPin, ledState);
81+
}
82+
}
6683
}
6784

68-
// set the LED using the state of the button:
69-
digitalWrite(ledPin, buttonState);
70-
7185
// save the reading. Next time through the loop,
7286
// it'll be the lastButtonState:
7387
lastButtonState = reading;

0 commit comments

Comments
 (0)