int buttonPin = 2; // the number of the pushbutton pin
int led1Pin = 13; // the number of the first LED pin
int led2Pin = 12; // the number of the second LED pin
int buttonState = 0; // current state of the button
int lastButtonState = HIGH; // previous state of the button (with pull-up)
unsigned long pressStartTime = 0; // when the button was pressed
bool longPressDetected = false;
void setup() {
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // using internal pull-up resistor
}
void loop() {
buttonState = digitalRead(buttonPin);
// Check for button press (LOW because of pull-up)
if (buttonState == LOW && lastButtonState == HIGH) {
// Button was just pressed
pressStartTime = millis();
longPressDetected = false;
}
// Check for button release (HIGH because of pull-up)
if (buttonState == HIGH && lastButtonState == LOW) {
// Button was just released
if (!longPressDetected) {
// If it wasn't a long press, it's a short press
if (millis() - pressStartTime < 1000) {
toggleLED(led1Pin);
}
}
}
// Check for long press while button is still held down
if (buttonState == LOW && !longPressDetected) {
if (millis() - pressStartTime >= 1000) {
longPressDetected = true;
toggleLED(led2Pin);
}
}
lastButtonState = buttonState; // save the current state for next loop
}
void toggleLED(int ledPin) {
digitalWrite(ledPin, !digitalRead(ledPin));
}