Use PIC Timer2 not Timer0 for accurate Interval Timing on an Embedded system

Recently I was struggling to achieve very accurately synchronised camera and light triggers for a real-time computer vision project that I was working on, my original PIC embedded system for triggering everything using a PIC micro-controller had a fairly reliable accuracy of about 250us which was sufficient for a few years, but for various reasons this needed to be reduced by a factor of 10 to about 25us. The problem was that as I reduced the timer’s overflow period it started to become quite inaccurate and erratic.

It is possible to achieve quite accurate timing on your embedded software system using a PIC, however it can take a bit of work to tune things. Most articles that introduce the use of timers on the PIC use the Timer0 module as an example, maybe because it has a ‘0’ in it?

Now, when using Timer0 to produce a repeated time interval, its High & Low overflow registers must be manually reset in the interrupt handler to setup the next time period, all while the timer is still counting away.

This it makes it difficult to know what values to put into the registers to get an accurate overflow period – you end up trying to account for the interrupt latency and counting assembly instructions in the interrupt handler to estimate times etc.

The upshot is that it’s hard to get a reliable overflow period with a desired accuracy when using Timer0.

Example, initial Timer0 setup code:

The best thing to do is to ditch Timer0 and switch to Timer2 instead. Timer2 automatically handles this kind of pattern (and it’s not much harder to use even though it’s got a ‘2’ in its name!).

When using Timer2 you don’t need to reload the overflow registers and so it is much easier to get an accurate and reliable overflow period! Have a look here if you need help in figuring how to setup Timer2 for your desired timing parameters – it’s very handy!

Once Timer2 is initialised in this manner, it will cycle automatically without the need to reload any values yielding a stable (and hopefully more accurate) time period.