LED turns on if button not pressed within 5 seconds

Hey all,

Hope all is well. Essentially I want the LED to stay off as long as the button in pressed in 5 second (or less) intervals. If the button is not pressed within 5 seconds, the LED should go off.

This is the code I have thus far. As of right now, the light always goes off after 5 seconds, no matter if I press the button or not. Thanks in advance for any help!

const int ledPin = 2;         
const int buttonPin = 3;

int buttonState = 0;          

void setup() {

 Serial.begin(9600);
 pinMode(ledPin, OUTPUT);    
 pinMode(buttonPin, INPUT);  
}

unsigned long startTime = 0;

void loop() {

 unsigned long currentTime = millis();
 
 buttonState = digitalRead(buttonPin);
 
 if (currentTime - startTime >= 5000) { 
     digitalWrite(2, HIGH);   
     if (buttonState == HIGH) {  
       currentTime = 0;
     }  
     if (buttonState == LOW) {
       currentTime = millis();
     } 
 }
}

kmaamari:
Hey all,

Hope all is well. Essentially I want the LED to stay off as long as the button in pressed in 5 second (or less) intervals. If the button is not pressed within 5 seconds, the LED should go off.

its not quite clear what your trying to do... when the arduino boots do you want the led on or off, right now your not telling which one. what starts the 5 second timer? what type of switch are u using a momentary push button switch or an on/off switch? it sounds like u want the led ON until the button is pressed within 5sec of start up? or do u just want a turn and led on and off with a momentary push button?

 if (currentTime - startTime >= 5000) { 
     digitalWrite(2, HIGH);   
}

This is the only place where you change the LED pin (BTW why don't you use const ledPin you defined?).
So pin 2 stays HIGH forever. I assume HIGH == off in your case, you did not tell

Do you have a pulldown resistor(10k) from pin 3 to GND?

const int ledPin = 2;        
const int buttonPin = 3;

int buttonState = 0;          

void setup() {

 Serial.begin(9600);
 pinMode(ledPin, OUTPUT);    
 pinMode(buttonPin, INPUT);  
}

void loop() {

   static unsigned long currentTime = millis();
 
   buttonState = digitalRead(buttonPin);

   if(buttonState == 1)        // if button pressed,
     currentTime = millis();  // reset timer
   if(millis() - currentTime > 5000) // else
     digitalWrite(ledPin, HIGH);  
   else
     digitalWrite(ledPin, LOW);   
}