 # Time count using millis()

Hi everyone,

I'm trying to apply a time counter using millis() into my system, the part of the code is as followed:

`````` if (speedrpm > 20)
{
lcd.setCursor(0, 0);
lcd.print(speedrpm);
seconds = millis()/1000;
lcd.setCursor(11, 1);
lcd.print(seconds);
if (seconds > 60){
seconds = 0;
++minutes;
lcd.setCursor(8, 1);
lcd.print(minutes);

}
if (minutes > 60){
++hours;
lcd.setCursor(5, 1);
lcd.print(hours);
minutes = 0;
}
}
``````

The timer starts counting just fine, but I cant seem to figure out a way so that for example, after 60 seconds, the minute will go up by 1 only and wait for the next 60 seconds,can anyone help me with a solution? Also, how do you set the counter back to 0 after for example 60 seconds because I try seconds = 0 and it doesnt work. Thank you very much.

You need to have an unsigned long variable to store a starting value of millis(), and do a subtraction.

It will help to study this excellent tutorial on Blink Without Delay.

Read Robin2’s discussion: Demonstration code for several things at the same time:

You completely reload seconds in `seconds=millis()/1000`
Setting seconds to zero will be overwriitten in next turn of the loop.

To get hours, minutes, and seconds since the Arduino started:

``````  seconds = millis()/1000;
minutes = seconds / 60;
hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
``````

To get hours, minutes, and seconds since a start time:

``````static unsigned long startTime = millis();

seconds = (millis() - startTime) /1000;
minutes = seconds / 60;
hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
``````

To re-start the timer: “startTime = millis();”