( When the button is pressed, the LED turns on. If the button is released, the LED turns off but if the button is continuously pressed for 5 seconds, the LED turns off )
const int buttonPin = 2;
const int ledPin = 13;
int buttonState = 0;
int lastButtonState = 0;
unsigned long buttonPressTime = 0;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH && lastButtonState == LOW) {
digitalWrite(ledPin, HIGH);
buttonPressTime = millis();
}
>
if (buttonState == LOW && lastButtonState == HIGH) {
digitalWrite(ledPin, LOW);
}
if (buttonState == HIGH && millis() - buttonPressTime >= 5000) {
digitalWrite(ledPin, LOW);
}
lastButtonState = buttonState;
}