Time for microcontrollers






by Ian Harris


Having the ability to tell the present time is a fairly handy feature when you make a microcontroller project. You might, for instance, need to actually display the time as a clock - on an LED display or a LED display panel. Or, you may want to just do something now and then - like turn a watering system on and off at various times of the day. Either way, knowing what the time is essential.

Typically microcontrollers have timers, which can be programmed to set to incrementally count on each instruction clock heartbeat. Timers also have dividers, which reduce the clock effectively, so that you can time longer periods. This is a great way of timing things that have to be done pretty continuously (for example, refreshing a display or checking for key input) but the problem with them is that they aren't extraordinarily accurate. It's very difficult to get a precise timing for (say) once per second. And if your clock is out by 1% which does not sound much, it means the actual time you're counting will be out by almost 432 minutes every month!

A better idea is to use the option on many microcontrollers of having a second clock source - but instead of using a 20Mhz crystal, a 32,768Hz crystal is utilized. Now that number 32,768 might seem a little familiar if you are comfortable thinking in binary. It's a nice number that divides very well by factors of two. So that you can quite exactly get a count of how many seconds have elapsed. Still, you're using timers and will have to take care that you reset the timer properly on overflow (otherwise, you'll finish up putting additional "time" in each second heart beat).

The best way is by utilising a seperate real time clock module. These modules, based on the M41T81S or DS1307 (there are several others) lets you query the time down to the millisecond via a two-wire protocol like I2C. These modules commonly have battery back up as well , meaning that even without power the time will continue to be correct. This also suggests that your microcontroller is free to not have to stress about keeping time and can concentrate on doing the actual work you have designed for it.

Using modules that have a particular purpose is a great way of prototyping different partss in your project and in this instance, also gets you pretty accurate,battery-backed time information.




About the Author: