const int BUTTON_PIN = 2;
const int LED_PIN = 21;
const unsigned long DEBOUNCE_DELAY = 50; // Debounce time in milliseconds
unsigned long lastDebounceTime = 0; // Variable to store the last time the button was pressed
int buttonState = HIGH; // Current state of the button (HIGH by default)
int lastButtonState = HIGH; // Previous state of the button (HIGH by default)
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT);
}
void loop() {
int reading = digitalRead(BUTTON_PIN); // Read the state of the button
// if (buttonState == LOW) Serial.println(buttonState);
// Check if the button state has changed
if (reading != lastButtonState) {
lastDebounceTime = millis(); // Reset the debounce timer
}
// Check if the debounce delay has passed
if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
// If the button state has changed and remained stable for the debounce delay
if (reading != buttonState) {
buttonState = reading; // Update the button state
// If the button is pressed (LOW), toggle the LED state
if (buttonState == LOW) {
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle the LED
}
Serial.print("Button State: ");
Serial.println(buttonState == LOW ? "Pressed" : "Released");
}
}
lastButtonState = reading; // Save the current button state for comparison in the next iteration
}