How do you plan to solve it?
const int button_pin = 4; // Pin connected to the button
unsigned long debounce_duration = 50; // Minimum time to debounce button (in milliseconds)
int previous_button_state = HIGH; // Previous state of the button
int current_button_state = HIGH; // Current state of the button
unsigned long last_debounce_time = 0; // Time when button state last changed
unsigned long press_start_time; // Time when button press starts
unsigned long release_time; // Duration of the button press
void setup() {
pinMode(button_pin, INPUT_PULLUP); // Configure button pin with internal pull-up resistor
Serial.begin(115200);
}
void loop() {
if (debounced_button_press_check(button_pin, LOW)) {
press_start_time = millis(); // Record the time the button was pressed
while (!debounced_button_press_check(button_pin, HIGH))
;
release_time = millis() - press_start_time; // Calculate the button release duration
if (release_time > 1000) {
Serial.println("Long press detected");
} else {
// Check for single or double press within a specific time frame
while (1) {
if (debounced_button_press_check(button_pin, LOW)) {
Serial.println("Double click detected");
break;
}
if ((millis() - press_start_time) > 400) {
Serial.println("Single click detected");
break;
}
}
}
}
}
//Checks for a debounced button press and returns true if detected, false otherwise.
bool debounced_button_press_check(int pin, bool expected_state) {
int button_reading = digitalRead(pin);
// If the button state has changed, reset the debounce timer
if (button_reading != previous_button_state) {
last_debounce_time = millis();
}
previous_button_state = button_reading;
// If the state has remained stable beyond the debounce duration, consider it valid
if ((millis() - last_debounce_time) > debounce_duration) {
if (button_reading != current_button_state) {
current_button_state = button_reading;
if (current_button_state == expected_state) {
return true; // Return true if the desired state is detected
}
}
}
return false; // Return false if no valid press is detected
}
Add a video of the output (know more)