#define BUTTON_PIN 18 // ESP32 pin GPIO18 connected to the button
#define LED_PIN 12 // ESP32 pin GPIO21 connected to the LED
int buttonState = HIGH; // the current state of the button
int lastButtonState = HIGH; // the previous state of the button
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long buttonPressCount = 0;
unsigned long lastPressTime = 0;
const unsigned long debounceDelay = 50; // debounce time in milliseconds
const unsigned long pressInterval = 500; // max interval between presses to consider as multiple presses
void handleButtonPresses();
void setup() {
Serial.begin(115200);
// Initialize the push button pin as an input
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Initialize the LED pin as an output
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW); // Ensure LED is off initially
}
void loop() {
handleButtonPresses();
}
void handleButtonPresses() {
int reading = digitalRead(BUTTON_PIN);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) {
buttonPressCount++;
lastPressTime = millis();
}
}
}
if ((millis() - lastPressTime) > pressInterval && buttonPressCount > 0) {
if (buttonPressCount == 1) { // SINGLE PRESS
Serial.println("Single press detected.");
digitalWrite(LED_PIN, HIGH); // Turn LED on
} else if (buttonPressCount == 2) { // DOUBLE PRESS
Serial.println("Double press detected.");
digitalWrite(LED_PIN, LOW); // Turn LED off
} else if (buttonPressCount >= 3) { // TRIPLE PRESS
Serial.println("Triple press detected.");
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED state
}
buttonPressCount = 0; // Reset the counter after action is taken
}
lastButtonState = reading;
}