Hi everybody,
I would like to read your opinions about this version of millis() (or should I write "BWD")
The use of delay() can be such a DELAY for newbees writing code that does not work they expect it.
Execute code only once every X seconds/minutes/hours is a task that comes along in a lot of cases. So I would call it a basic programming-technique.
delay(2000) is written down very quickly while something like
unsigned long currentMillis = millis();
if ( currentMillis - expireTime >= TimePeriod ) {
lastMillis = currentMillis;
etc. takes more time to write and it is something that has no selfexplaining name
recently I came across this version that reduces how much you have to write and offers a more selfexplaining name
//nbt nonblockingtimer using millis()
//this function checks if a timestamp containing milliseconds passed as first parameter
// was made more than
// X milliseconds in the past then second parameter "TimePeriod" specifies.
// if yes the function returns true and automatically updates the variable that keeps the timestamp
// if no just returns false
boolean TimePeriodIsOver (unsigned long &expireTime, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - expireTime >= TimePeriod )
{
expireTime = currentMillis; // set new expireTime
return true; // more time than TimePeriod) has elapsed since last time if-condition was true
}
else return false; // not expired
}
unsigned long MyTestTimer = 0;
void loop(){
// check if the timestamp-value of variable "MyTestTimer" was made more
// than 1000 milliseconds in the past.
// behaviour: execute "DoThings" only once every 1000 milliseconds
if ( TimePeriodIsOver(MyTestTimer,1000) ) {
DoThings;
}
Of course any solution has its pro's and con's
So I would like to read from you your opinion.
My opinion is: if all those simple "Blink-LED", "read out sensor and Serial.print" examples
would use this construction newbees would have to think over the code 10 minutes longer once at the beginning
of their learning-curve and avoid a lot of help-less hours trying to make code work with delay() that really cannot work with delay()
best regards Stefan