Probably you already know how to use millis() not to block your code. In this short article I am going to show how to use it very easily in the code to have it more transparent and effective.
In the next code we are going to run 3 processes independantly, where the 1st process executes every 200 milliseconds, the 2nd process executes every 5 seconds and the 3rd process executes every 29 seconds.
The core of the solution is in the following function MillisTimer:
bool MillisTimer(unsigned long* t, long waitMillis) {
unsigned long actualTime = millis();
if ((actualTime - *t) > waitMillis) {
*t = actualTime;
return true;
}
if (actualTime < *t) *t = actualTime;
return false;
}
This function returns true if the time (the value waitMillis) has expired and false if the right time did not come yet. As we know, millis() counts from zero every millisecond and overflows after 50 days when it starts to count from zero again. In the function we treat this with the last if sentence.
If we have this function then the code is very transparent and simple:
First we define unsigned long variables for counting and we initialize them in the setup:
unsigned long every200millis, every5seconds, every29seconds;
void setup() {
every200millis = millis();
every5seconds = every200millis;
every29seconds = every200millis;
}
And finaly we run our 3 processes in the loop:
void loop() {
if (MillisTimer(&every200millis, 200)) DoProcess1();
if (MillisTimer(&every5seconds, 5000)) DoProcess2();
if (MillisTimer(&every29seconds, 29000)) DoProcess3();
}
This code runs these 3 processes independantly. Of course, if you do not block the code in processes with delay() or "while" or "for" sentences.
Comments
Please log in or sign up to comment.