/*
Materials:
LED
Resistor 220Ω
Push button switch
1. Connect LED anode to digital pin 9 of the arduino board.
2. Connect LED cathode to resistor.
3. Connect resistor to GND of the arduino board.
4. Connect Button leg to digital pin 7 of the arduino board.
5. Connect Button other leg to GND of the arduino board.
*/
// Define variables
const int buttonPin = 7; // Digital pin for the push button
const int ledPin = 9; // Digital pin for the LED
int buttonState = LOW; // Current state of the button
int lastButtonState = LOW; // Previous state of the button
unsigned long lastDebounceTime = 0; // Last time the button was toggled
unsigned long debounceDelay = 50; // Delay time for debounce
void setup() {
pinMode(buttonPin, INPUT); // Use the internal pull-up resistor
pinMode(ledPin, OUTPUT);
}
void loop() {
int reading = digitalRead(buttonPin);
// Check if the button state has changed
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
// Check for button debounce
if ((millis() - lastDebounceTime) > debounceDelay) {
// Update the button state only if it has been stable
if (reading != buttonState) {
buttonState = reading;
// Toggle the LED state when the button is pressed
if (buttonState == LOW) {
digitalWrite(ledPin, !digitalRead(ledPin));
}
}
}
lastButtonState = reading;
}