millis() help

Trying to get the light to stay on for 2 minutes after a trigger. Doesn't work... light comes on with trigger and turns off right away, after the trigger goes away. Using IR sensors as the trigger.

void loop(){

// listen for incoming clients, and process qequest.
checkForClient();

unsigned long light1;
unsigned long light2;

//Motion for light 1
if (digitalRead(4) == HIGH)
{
light1 = millis();
digitalWrite(6, HIGH);
}

if (millis() - light1 >= 120000UL)
{
digitalWrite(6, LOW);
}

//Motion for light 2
if (digitalRead(5) == HIGH)
{
light2 = millis();
digitalWrite(7, HIGH);
}

if (millis() - light2 >= 120000UL)
{
digitalWrite(7, LOW);
}

}

You need to declare your light? variables as "static" so they remember their values over subsequent iterations of the loop().

At the moment light1 and light2 will either be equal to millis(), or 0*.

  static unsigned long light1;
  static unsigned long light2;
  • Actually, undefined, but in practice on the Arduino it's 0.

Thanks. That did it!

I haven't seen anywhere on the internet that people make them static.

Generally, because most people make them global. As local (non-static) variables, you get a new copy on each iteration of loop. The value does not persist from one iteration to the next. Making them either static or global ensures that the value DOES persist.

That doesn't work.

This is too lame to even comment on. "I expected the code to do such and such. Instead, it did this and that" would be so much more helpful. That might even present itself as a clue.