Go Down

Topic: Control time library. (Read 316 times) previous topic - next topic

albuino

Dec 20, 2012, 06:40 pm Last Edit: Dec 20, 2012, 06:42 pm by albuino Reason: 1
Hi,

I'd like to ask whether someone knows a good library to manage times.
For example, we usually write this code:

Code: [Select]

unsigned long previousMilis;
int time = 1000;
setup {previousMilis= millis();}
loop {if(millis() - previousMillis > time) {previousMillis = millis();}}


It'd be much easier by a library expresion:

Code: [Select]

TimeLibrary myTime;
int time = 1000;
loop {if(myTime.check(time)) {}}


Our sketchs would be much less tedious to manage.

Thanks.

robtillaart

can be made but one of the problems is that such a function has some function call overhead which may or may not affect your program flow. For millis() it is probably not too bad, for micros the story is quite different.

The code for your function is something like this.
Code: [Select]

boolean checkTimeElapsedSinceLastCall(unsigned long t)  // a shorter name is possible ;)
{
  static unsigned long prev = 0;
  unsigned long now = millis();
  if (now - prev >= t)
  {
     prev = now;
     return true;
  }
  return false;
}


have fun ;)
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

PeterH

Somebody did write a timer library that enabled you to have a function called after a delay, or at regular intervals. The code needed to implement that behaviour directly is pretty simple and not substantially more complex than the code needed to do the equivalent behaviour using the library, but the library is there if you want to use it.

albuino

#3
Dec 20, 2012, 09:27 pm Last Edit: Dec 20, 2012, 09:29 pm by albuino Reason: 1
You are right. The robtillaart's function is enough. Although I will need to rewrite the function to use in different contexts.

Go Up