millis() vs. elapsedMillis ?
are there any DISadvantages in using lib elapsedMillis() over millis() ?
millis - Question about ElapsedMillis() library and state machines - Arduino Stack Exchange
Using elapsedMillis for multiple delays in tone() function
I'm thinking about writing an article* about how to implement cooperative multi-tasking on Arduino-compatible microcontrollers. Working title: Beyond "Blink without Delay". Much of the article will talk about ways structure a program to simplify the handling of multiple concurrent "tasks" with different timing requirements, based on my own experience.
At a lower level, I'd like to discuss the pros and cons of the various methods to measure task time intervals. At minimum I'll cover the blink-without-delay method based on millis(), as well as the elapsedMillis library. I've tried a few different methods, including the Ticker library, but have come to rely exclusively on elapsedMillis for all my projects. But before I go off and profess my love for elapsedMillis, I'd like to get your input.
For reference, here's a brief synopsis of the blink-without-delay/millis() method:
unsigned long currentTime, previousTime;
unsigned int taskDelay = 300;
void loop() {
currentTime = millis();
if ((currentTime - previousTime) > taskDelay) {
previousTime = currentTime;
// Perform task
}
} And here's the elapsedMillis equivalent:
elapsedMillis taskTimer;
unsigned int taskDelay = 300;
void loop() {
if (taskTimer > taskDelay) {
taskTimer = 0;
// Perform task
}
}The key advantage of the elapsedMillis method is that the code is more concise and readable. It also eliminates any perceived issue with millis() rollover (which isn't really an issue with unsigned variables).
A disadvantage is the minor "time slippage" that occurs in the delay between the compare if (TaskTimer > TaskDelay) and resetting the timer taskTimer = 0. This is only an issue if the cumulative delays need to maintain long-term timing accuracy (a rare situation I think).
In addition to "going deep" on the two methods shown above, I'l also provide a brief survey of other timing methods, including Ticker and also the EVERY_N_MILLISECONDS method provided by the FastLED library.
What do you folks think? What's your preferred method, and why?
*If you want to see examples of my other articles, check here.