1919 by David A. Mellis
2020 modified 30 Aug 2011
2121 by Limor Fried
22+ modified 28 Dec 2012
23+ by Mike Walters
2224
23- This example code is in the public domain.
25+ This example code is in the public domain.
2426
2527 http://www.arduino.cc/en/Tutorial/Debounce
2628 */
2729
2830// constants won't change. They're used here to
2931// set pin numbers:
30- const int buttonPin = 2 ; // the number of the pushbutton pin
31- const int ledPin = 13 ; // the number of the LED pin
32+ const int buttonPin = 2 ; // the number of the pushbutton pin
33+ const int ledPin = 13 ; // the number of the LED pin
3234
3335// Variables will change:
3436int ledState = HIGH; // the current state of the output pin
@@ -43,6 +45,9 @@ long debounceDelay = 50; // the debounce time; increase if the output flicker
4345void setup () {
4446 pinMode (buttonPin, INPUT);
4547 pinMode (ledPin, OUTPUT);
48+
49+ // set initial LED state
50+ digitalWrite (ledPin, ledState);
4651}
4752
4853void loop () {
@@ -62,11 +67,20 @@ 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+ }
6680 }
6781
68- // set the LED using the state of the button :
69- digitalWrite (ledPin, buttonState );
82+ // set the LED:
83+ digitalWrite (ledPin, ledState );
7084
7185 // save the reading. Next time through the loop,
7286 // it'll be the lastButtonState:
0 commit comments