const int buttonPin = 2; // Pin where the button is connected
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() {
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
Serial.begin(9600);
}
void loop(){
int buttonState = digitalRead(buttonPin);
// 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
Serial.println("Button pressed!");
buttonPressed = true;
} else if (buttonState == HIGH) {
// Button has been released
buttonPressed = false;
}
}
lastButtonState = digitalRead(buttonPin);
}