/* Push button and led - week 08 - exercice 2 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 3 to ground - pushbutton attached from pin 4 to +5V - 10 kilohm resistor attached from pin 4 to ground The program: Turns an LED on when the pushbutton is activated once (and keeps it on) and turns it back off when it's pressed again. written 22 March 2021 by A.de Vries for FABACADEMY 2021 */ // Set pin numbers: const int buttonPin = 4; // pushbutton pin n° const int ledPin = 3; // LED pin n° // Variables: int ledState = LOW; // current state of the output pin ("OFF") int buttonState; // current reading from the input pin int lastButtonState = LOW; // 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; // last time the button was toggled unsigned long debounceDelay = 50; // debounce waiting time (delay) void setup() { pinMode(buttonPin, INPUT); pinMode(ledPin, OUTPUT); // set initial LED state digitalWrite(ledPin, ledState); } void loop() { // read the state of the switch: int reading = digitalRead(buttonPin); // check to see if you just pressed the button and waited long enough // since the last time to ignore potential noise: // In case the switch changed (due to bounces): if (reading != lastButtonState) { // reset debounce timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // if the reading has been there for longer than the debounce // delay, take it as the actual current state: // if button state has changed: if (reading != buttonState) { buttonState = reading; // only toggle the LED if the new state is HIGH if (buttonState == HIGH) { ledState = !ledState; } } } // set the LED: digitalWrite(ledPin, ledState); // save the reading in lastButtonState: lastButtonState = reading; }