const int buttonPin = 2; // Pin number where your button is connected
const int ledPin = 13; // Pin number where your LED is connected
// Variables
int buttonState = HIGH; // Current state of the button (HIGH or LOW)
int lastButtonState = HIGH; // Previous state of the button
boolean longPressDetected = false; // Flag to track long press detection
unsigned long longPressStartTime = 0; // Time when the button was pressed (milliseconds)
unsigned long longPressDuration = 2000; // Define the long-press duration in milliseconds
unsigned long debounceDelay = 200; // Delay to ignore subsequent changes (milliseconds)
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int reading = digitalRead(buttonPin);
// Check if the button state has changed
if (reading != lastButtonState) {
lastButtonState = reading;
// Button pressed
if (reading == LOW) {
longPressStartTime = millis(); // Record the start time of button press
delay(debounceDelay); // Delay to ignore subsequent changes
longPressDetected = false; // Reset the long-press detection flag
}
} else {
// Button released
if (reading == HIGH) {
// Check for long-press condition
if (millis() - longPressStartTime > longPressDuration) {
if (!longPressDetected) {
// Perform actions for long press (e.g., turn on the LED)
digitalWrite(ledPin, HIGH);
Serial.print("Long press duration: ");
Serial.println(millis() - longPressStartTime);
longPressDetected = true; // Set the flag to avoid continuous processing
}
}
}
}
// Update the LED state based on the long-press detection
digitalWrite(ledPin, longPressDetected ? HIGH : LOW);
}