int buttonPin = 5; // Pin connected to pushbutton
int ledPin = 2; // Pin connected to LED
bool buttonPressed = false; // Flag to indicate if the button has been pressed
bool lastButtonState = HIGH; // Previous state of the button
unsigned long lastDebounceTime = 0; // Time the button state last changed
unsigned long debounceDelay = 50; // Debounce time (50 milliseconds)
void setup()
{
Serial.begin(115200);
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buttonPin, INPUT_PULLUP); // Set pushbutton pin as input
}
void loop() {
int buttonState = digitalRead(buttonPin); // Read input from pin 5
// Check if the button state has changed
if (buttonState != lastButtonState) {
lastDebounceTime = millis(); // Reset the debouncing timer
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button state has been stable for the debounce delay
if (buttonState == LOW && !buttonPressed) {
// Button has been pressed
digitalWrite(ledPin, HIGH); // Turn on LED
Serial.println("Button pressed!");
buttonPressed = true;
} else if (buttonState == HIGH) {
// Button has been released
buttonPressed = false;
}
}
lastButtonState = buttonState; // Update the last button state
}