const int buttonPin = 7; // Pin where the button is connected
const int ledPin = 8; // Pin where the LED is connected
int buttonState = 0; // Variable to store the button state
int lastButtonState = 0; // Variable to store the last button state
unsigned long lastDebounceTime = 0; // Variable to store the last debounce time
unsigned long debounceDelay = 50; // Debounce time (in milliseconds)
void setup() {
pinMode(buttonPin, INPUT); // Set the button pin as an input
pinMode(ledPin, OUTPUT); // Set the LED pin as an output
}
void loop() {
int reading = digitalRead(buttonPin); // Read the state of the button
// Check if the button state has changed
if (reading != lastButtonState) {
// Reset the debounce timer
lastDebounceTime = millis();
}
// If the state has been stable for longer than the debounce delay
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button state has changed
if (reading != buttonState) {
buttonState = reading;
// If the button is pressed
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); // Turn the LED on
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Turn the LED off
}
}
}
// Save the reading. Next time through the loop, it'll be the lastButtonState
lastButtonState = reading;
}