// variable holding the button state
int buttonState;
// variable holding previous button state
int previousButtonState = LOW;
// variable holding the LED state
int ledState = HIGH;
int buttonPin = 2;
const int ledPin = 13;
// millis always stored in long
// becomes too big for int after 32,767 millis or around 32 seconds
// timestamp of a previous bounce
long previousDebounceTime = 0;
// debounce time in millis, if the LED is still quirky increase this value
long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// for now it's the same as in previous example
int reading = digitalRead(buttonPin);
// if the previous reading is different than the previous button state
if (reading != previousButtonState) {
// we'lll reset the debounce timer
previousDebounceTime = millis();
}
// if the reading is the same over a period of debounceDelay
if ((millis() - previousDebounceTime) > debounceDelay) {
// check if the button state is changed
if (reading != buttonState) {
buttonState = reading;
// toggle the LED state only when the button is pushed
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
// set the LED:
digitalWrite(ledPin, ledState);
// save current reading so that we can compare in the next loop
previousButtonState = reading;
}