//Debounce
/* Each time the input pin goes from LOW to high (e.g. because of a push-button press),
the output pin is toggled from LOW to HIGH or HIGH to LOW. There's a minimum delay
between toggles to debounce the circuit (i.e to ignore noise)
The Circuit:
LED attached from PIN 8 to ground through 220 ohm resistor.
Push button attached to pin 2 from +5V
10K resistor attached to pin 2 from ground
*/
//Constants won't change. They're used here to set pin numbers:
const int buttonPin = 2; //The number of the pushbutton pin.
const int ledPin = 8; //The number of the LED pin.
//Variables will change:
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 following variables are unsigned longs because the time, measured in
//milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; //The last time the output pin was toggled.
unsigned long debounceDelay = 50; //The debounce time; increase if the output flickers
void setup()
{
Serial.begin(115200);
Serial.println("ready..");
pinMode(ledPin, OUTPUT); //Initialize the LED pin as an output.
pinMode(buttonPin, INPUT); //Initialize the pushbutton pin as an input.
digitalWrite(ledPin, ledState); //Set initial LED state
}
void loop()
{
int reading = digitalRead(buttonPin); //Read the state of the switch into a local variable:
//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 (reading != lastButtonState)
{
lastDebounceTime = millis(); //Reset the debouncing timer
}
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:
{
if (reading != buttonState) //If the button state has changed:
{
buttonState = reading;
if (buttonState == HIGH) //Only toggle the LED if the new button state is high
{
ledState = !ledState;
}
}
}
digitalWrite(ledPin, ledState); //Set the LED:
lastButtonState = reading; //Save the reading. Next time through the loop, it'll be the lastButtonState:
}