need help to get around useless "delay" function

i have a led light that i am turning on for 4 seconds with a switch. the switch only stays closed for a fraction of a second. the delay function works but it shuts down all processing and i can't have that.

does anyone know how to substitute the millis function for the delay function?
here's the code that works and compiles except for the delay function issue.

void setup() {
Serial.begin(9600);

}
// put your main code here, to run repeatedly:
void loop() {

pinMode(2, INPUT_PULLUP);
int sensorVal = digitalRead(2);
Serial.println(sensorVal);
delay (10);
pinMode(7, OUTPUT);// initialize digital pin 7 as an output.
if (sensorVal == HIGH) {
digitalWrite(7, LOW);
delay(4000);
}
else {
digitalWrite(7, HIGH);

}
}

You are in luck!
There is a sketch that comes with the IDE call "Blink Without Delay".

Master the technique as you will use it a lot.

i know about blink without delay and i can't seem to modify it for using a switch to turn on the light.

Have a look at several things at a time. It is an extended example of the BWoD technique

...R

What does this do?

if(millis() - lastMillis >= 4000UL)
{
some code
}

 if(millis() - lastMillis >= 4000UL)
  {
     some code
  }

Will execute "somecode" 4 seconds after millis is enabled after a reset.
While this:

 if(millis() - lastMillis >= 4000UL)
  {
     lastMillis = lastMillis + 4000UL;
     some code
  }

will execute every 4 seconds

Will execute "somecode" 4 seconds after millis is enabled after a reset.

It was a question for OP

:kissing: I should have said:
@killedoff
What does this do?

@ killedoff
What would this do?

if(millis() - lastMillis >= 4000UL)
{
//**********
if (sensorVal == HIGH)
{
digitalWrite(7, LOW);
lastMillis = millis();
}
else
{
digitalWrite(7, HIGH);
}
//**********
}

Sorry, didn't mean to mess up the lesson :frowning:

i need the led light to stay on for 4 seconds even though the switch is not being closed. also, i want the 4 seconds to reset if the arduino sees the switch closed before the 4 seconds has passed. if arduino does not the switch closed after 4 seconds, the the light should go off.
thanks to everyone that replied.

Hello,

See this example.

@killedoff
Will you explain what happens in the example in reply #7?