[riot-devel] hwtimer library with multiple timers (not channels)

Joakim Gebart joakim.gebart at eistec.se
Wed Sep 10 19:57:10 CEST 2014

I wonder if anyone has thought about how to implement the hwtimer
arch-specific parts for a cpu where there are multiple timers that run

I am working on a port for the Freescale Kinetis K60 CPU which has the
following abilities:

4 hardware programmable interrupt timers, each with the following properties:

 - Fixed frequency (48 MHz in my application)
 - Down counting (easily reversed in software by subtracting the
current time from the target time)
 - Interrupts are called when the counter value reaches zero.
 - Counter register represents how much time remains until the
interrupt is triggered.
 - Non-writable counter register
 - Changing the counter value can be acheived by disabling the timer,
setting a new load value, starting the timer. NOTE: The timer will be
reset to the new load value.

The problems I have are the following:

hwtimer_now(): Difficult to implement since it is expected that the
timer is increasing, and because of the method of setting the
interrupt time the counter value will only be reflecting how far along
the current countdown we are. I.E. calling hwtimer_set() on my CPU is
equivalent to calling timer_reset(HWTIMER) immediately followed by
hwtimer_set(); on the STM32's for example.

hwtimer_set_absolute(): There is no absolute reference in this situation.

Below are the possible solutions I have been thinking about:

Dedicating (wasting) one timer to act as absolute counter.
This involves setting the timeout to 0xffffffff during hwtimer_init()
and using this dedicated timer for hwtimer_now() calls and count
backwards from hwtimer_now() when dealing with hwtimer_set_absolute().

Pros: Works with ps, scheduler statistics, vtimer with a slight
precision loss since some microsecond might be wasted computing the
actual desired delay from hwtimer_now() and the argument to

Cons: Wastes one timer channel for a dumb counter, counter will still
overflow after only 89 seconds (?) if running at 48 Mhz compared to 71
minutes if counting at 1 MHz.

Dedicating two timers for absolute counter.
Same as above, except use timer hardware chaining available in the CPU
to get one large 64 bit 48 MHz counter instead.

Making hwtimer_now() always return zero.
This will have a negative impact on scheduling statistics, as well as
the vtimer library.

Ignoring the problem and letting hwtimer_now() jump about.
This will probably break the vtimer library.

What would be my best approach in this scenario?

Best regards,
Joakim Gebart
Software and Hardware Engineer
Eistec AB

Aurorum 1C
977 75 Luleå
Tel: +46(0)70-570 66 35
joakim.gebart at eistec.se

More information about the devel mailing list