I am making a timer function using millis(). I have to make a stopwatch and current time function too and all three have to be able to run simultaneously.
Do you want a stopwatch (counting up) or a count-down timer ?
There are two ways for a count-down timer:
Use millis() itself. The advantage is that it has millisecond precision and nothing can be missed. The disadvantage is that millis() could run past the zero point, and you need some extra code to deal with that.
Use a millis-timer and solve everything in that millis-timer.
Try again with all our tips and show us the new sketch.
Is it for school ?
In your Arduino loop(), you have a millis timer with:
if(millis() - timerCurrentMillis >= 1000) {
It only becomes active once per second. That means the Arduino is doing nothing most of the time. You can add many more millis-timers.
With a little tweaking I could run 400 millis-timers on a Arduino Uno here.
The variable name 'timerCurrentMillis' is confusing.
Could you follow the Blink Without Delay example ? https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay.
It is the value of millis() that is stored to be able to compare it. You could call it 'previousMillis' or something with the term "timestamp" or so.
The millis() could meanwhile have changed. That can be fixed with by using a variable instead of the millis().
// global variables
unsigned long previousMillis;
const unsigned long interval = 1000;
...
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
previousMillis = currentMillis; // normal millis-timer, is safe and works always
// lots of code
}
It can be even more improved for a clock or countdown timer.
If there is other code in the Arduino loop(), then millis() could be passed the interval and everything shifts forward in time. That can be prevented by staying in sync with the time.
// global variables
unsigned long previousMillis;
const unsigned long interval = 1000;
...
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
previousMillis += interval; // special millis-timer, stay in sync with time
// lots of code
}