Lately I’ve become more and more fan of the Arduino microcontroller. I really like how easy it is to work with; the accompanying IDE plus the huge amount of community support and libraries available.

However, for a project I needed to be able to sample input audio at a certain frequency and this required me to understand a bit more deeply on how to configure the ATMEGA328 timer registers. In this post I’ll show you how to call a user function at a period of one millisecond.

I decided to use the 8-bit Timer2 which is one of the timers in the ATMEGA328. The principle is to let the timer counter register increment it’s value at a specific clock rate and eventually trigger an interrupt when it overflows (FF:s -> 0:s). Then we just need to load it with an appropriate value to make it overflow every one millisecond, and install our interrupt handler routine in the interrupt vector table. Sounds complicated? It’s really not when you’ve found all the necessary registers to play with. Keep on reading.

After some tedious reading in the ATMEGA328 datasheet (and googling!) I came up with this code:

The code should be pretty clear from the comments but let me just elaborate a bit on the calculations:

First of all, the observant reader will notice that the above code will only be accurate for a CPU running at 16MHz since the calculations are based on this frequency. By using the prescaler feature we can increase the time between our interrupts a bit, and by using a prescaler value of 128 we simply tell
the timer to increase it’s value every 128:th clock cycle (or every 8:th microsecond if the CPU frequency is 16MHz). Now that we now this timer interval , we can calculate the number of steps for the timer register by dividing our target value 1ms, by 8us, which gives us the value 125.
Finally, since the timer counter will generate an interrupt on overflow, we simply subtract 125 from the maximum counter value, 256, which gives us the final value 131.

To prove that this is actually working I attached my chinese pocket oscilloscope from Jyetech to the digital output that I’m writing to in the code. Enjoy:

Joy oh joy! one interrupt every one millisecond

Well, what’s the use of this, you might ask? I’ll tell you! You could do a number of cool things, like your own synthesizer, music sampling (with limited frequency response though…) or perhaps a small scheduler for light weight threading! Impressive, huh? =)

Well, There you have it! Now go and write something useful. You’ll see more related topics from me in the future.