Programming Questions / Millis to trigger LED for set time then reset

Programming Questions / Millis to trigger LED for set time then reset

so Im trying to make a LED turn on for a set interval (1 second) when that function is called. the function will only be called if an IF statement in the main loop is true. I would then like the LED to turn back off after the 5 seconds then "reset" to allow me to call the function again if that same IF statement is true. I have been trying this for a couple days and feel like im missing something basic in my code to allow this.

any tips would be awesome.

int led = 13;

void setup() {
pinMode(led, OUTPUT); // initialize LED output
}

void loop()
{
if (something=something)
{
timers();
}
//the led should always be off until the timers() function is called and its only on for the interval time
//the led is turned back off after the time has expired
//timers should "reset" its self, allowing for it to be called again and again regardless of time
}

void timers() {

unsigned long previousMillis = 0;
const long interval = 1000;
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval){
previousMillis = currentMillis;
digitalWrite(led, HIGH); //turns led on for the interval
else
digitalWrite(led, LOW); //turns back off when the time is greater than the interval
}
}

sketch_mar27a.ino (783 Bytes)

Blink without delay is a bit confusing because it shows a repeating timer and it is hard to se what start and stops the timing. Here's a few things I see.

void loop()
{
If (somthing==thisThing)
 {
  Timers();
 }
}

Since the somthing that triggers the timing event may not be true by the time the timers expires (such as a button press) you should call timers() every time through loop and do all your decision making there.

void loop()
{
Timers();
}

I like that your using local variables but they are forgotten every time the function ends. So when it needs to remember a variable the next time it is called you need to make it static.

static unsigned long previoudMillis=0;

Ok now to make a one shot timer.

if (something==thisThing)
{
 PreviousMillis=currentMillis;  // this starts the timer it must be inside of a conditional statement
 DigitalWrite(led,HIGH);    //do stuff when the timer is started
}

If (currentMillis-previousMillis >= interval) // this stops the timer
{
 DigitalWrite (led,LOW); // do stuff when time is up
}

Hope this helps,
Les

EDIT: please excuse the grammatical errors. Darn phone!