Understanding millis.

So, I am trying to make a countdown timer, so x time (5 seconds = 300000millis) after a button is pressed, something will happen.

When the button is pressed, lightOnMillis is sampled.

At the end of scetch, the following code samples lightOffMillis and compares the result and either performs actions or not.

However, what happens is that if millis is set to 300000, the light stays on about 30 seconds, highest I have tried and still working is 900000, and it stays on a little longer. If I set the intervalMillis to 1000000, the light is always off.

lightOffMillis=millis(); if (lightOffMillis - lightOnMillis <= intervalMillis) { level = 1; led = 7; lightOnMillis = 0; }
  1. Make your code tags with instead of <>. They’re bbc not html.

  2. You need to show the complete code. You haven’t shown what types the variables are and that might make a big difference.

  3. Usually you are looking for the time difference to be greater than some interval. You’re checking for it to be less than so the stuff inside runs before the timer is up and then you set lightOnMillis back to 0 which pretty much makes that impossible to be less than so it will probably only run once.

gbremset wrote (in part):

(5 seconds = 300000millis)

No, 5 seconds = 5000 milliseconds.

My apologies, I meant 5 minutes, not 5 seconds.

Please find attached entire code for this project, which is a nightlight for my daughter using 6 LED’s (I have added a 7th led on pin 13 for another part of the project which isn’t there yet)

As a note, everything else works as planned, only thing I need now is the 5 minute off timer during nighttime.

led_cycle_with_level_and_time.ino (9.62 KB)

Another way of saying what was already said above, milliseconds /1000 = seconds.

Try putting something like the following in your code for temporary debugging and understanding.

Serial.print("lightOffMillis: ");
Serial.print(lightOffMillis / 1000);             // divided by a thousand to get seconds

Serial.print("\t lightOnMillis : ");
Serial.print(lightOnMillis / 1000);              // divided by a thousand to get seconds

Serial.print("\t intervalMillis : ");
Serial.println(intervalMillis / 1000);           // divided by a thousand to get seconds

To get an even better understanding of millis(), change the values above to print in minutes instead just for the exercise.

The demo Several Things at a Time illustrates the use of millis() to manage timing. It may help with understanding the technique.

...R