Computing stuff tied to the physical world

MilliTimer example

In Software on Mar 16, 2012 at 00:01

The MilliTimer class in JeeLib is a convenient way to perform time-related activities while doing other things at the same time. See also these weblog posts about wasting time and other ways of scheduling multiple tasks. And if you’re willing to learn a new programming language: check out this post.

With just the basic Arduino library support, i.e. if you have to do everything with delay() calls, it’s a lot harder to do things like making two LEDs blink at an independent rate – as in this blink_timers example:

Screen Shot 2012 03 09 at 11 59 12

This illustrates a simple way of using the millisecond timers: calling one with “poll(ms)” will return true once every “ms” milliseconds. The key advantage is that you can do other things in between these calls. As in the above example, where I used two independent timers to track the blinking rate of two LEDs.

This example uses the millitimers in automatic “retrigger” mode, i.e. poll() will return true every once in a while, because whenever poll() returns true, it also re-arms the timer to start over again.

There may be cases where you need a one-shot type of trigger. This can also be handled by millitimers:

    MilliTimer t;
    while (...) {
      if (t.poll())

When used in this way, the timer will go off only once, 123 milliseconds after having been set.

There are a few other things you can do with millitimers, like finding out whether a particular timer is running, or how many milliseconds remain before it will go off.

These timers only support timeouts in the range of 1..60,000 milliseconds. For longer timeouts, you’ll have to do a bit more work yourself, i.e. to wait one hour you could do:

    MilliTimer timer;
    int seconds = 3600;
    while (...) {
      if (timer.poll(1000) && --seconds <= 0)
        Serial.println("ding dong");

Note that the MilliTimer class implements software timers, and that you can have as many as you like. No relationship to the hardware timers in the ATmega, other than that this is based on the Arduino runtime’s “millis()” function, which normally uses hardware TIMER0 internally.

For a more advanced mechanism, see the Scheduler.

  1. If someone needs millisecond-timers wich can handle really long intervals, they should check what I’ve made, because those timers support the full Arduino timer range (i.e. 49 days) Its stored on github:

  2. I think your last code snippet counts up 60 seconds, not 60 minutes (?)

  3. I have happily been using this scheduler written in C++ in my past 2 project :

    It requires writing a separate class for each type of task, but I found it quite nice to work with (or am I a masochist?). It forces to separate the processing into separate functions/methods, instead of having one giant loop() that is barely readable.

Comments are closed.