Creating custom timer interrupts for arduino

Arduino boards are awesome. Even more awesome is the fact that there’s so much documentation out there on using them.

A very popular timer interrupt library for Arduino is MsTimer2, which has a resolution of 1 millisecond. If your project requires more resolution however, you’re a bit out of luck. Fortunately, it’s rather easy to increase the resolution of the timer library with a few modifications.

I stumbled across this blog post from 2010 where the author had already gone over the task of reading the datasheet for Amtel’s ATMEGA*** series of microcontrollers, and understanding the way the timer registers work. This particular post is concerned with timer2. Of interest is this part of the documentation:

 /* We need to calculate a proper value to load the timer counter.
   * The following loads the value 131 into the Timer 2 counter register
   * The math behind this is:
   * (CPU frequency) / (prescaler value) = 125000 Hz = 8us.
   * (desired period) / 8us = 125.
   * MAX(uint8) + 1 – 125 = 131;
   */
Indeed, the method above and the sketch included in the blog post are exactly what was used to build MsTimer2. Using the knowledge therein, I modified it slightly to create my own timer library with a resolution of 40 microseconds. Following the logic above, for a period of 40 microseconds and a prescaler value of 128 (My board runs at 16MHz), I have:
40 / 8 = 5.
Therefore, the value to be loaded into the timer 2 register is  MAX(uint8) – 5 = 256 – 25 = 251.
Then, in the library’s overflow function, you increase some variable (count in this case) by the period: 40 microseconds.
NOTE: These modifications now mean you have to pass the period into the library in microseconds, and not milliseconds. The full modified library can be found on Github at the following link:

 

 

The library is also fairly robust so it works on a plethora of Arduino boards. Peruse the .cpp file to see if your board is supported. If it isn’t simply add an if statement and include your board, or take out the statements and put in the appropriate prescaler value.

 

Enjoy.

Leave a comment