Have you used pulse-width modulated (PWM) outputs to dim a light emitting diode (LED) or control the speed of a motor?  Then you've used timer/counters. To generate a PWM signal, a counter counts from 0 to it's maximum, let's say that's 256 to keep things simple (so that'd be an 8-bit counter). A PWM generator has its output low when the count is below a specified value, and high when it's equal to or above. If we wanted full brightness on an LED, we'd set that PWM threshold to 0 so that the output will always be high. If we wanted it at 50% we'd set the threshold to 128 (assuming a fairly linear response curve for the LED, which is probably reasonable at the 50% point, but generally not near the minimum and maximum values). That way the output would be low half the time and high half the time.

Counters are useful when you need to keep track how often some event occurs. If that event can be converted to a digital pulse, you can count it. If the event corresponds to one revolution of a wheel, for example, counting them and checking the count every so often would tell you how fast the wheel is turning.

That brings us to another use of timers: keeping track of time.  We can set up a timer to let us know every time a second has gone by. We could regularly check the time to see if a second has passed (which is usually referred to as polling) or we could have the timer generate an interrupt every second. Which we use partly depends on how critical it is that we do something as soon as possible when that time is up.  We could set this up to happen once (let me know in one second) or repeatedly (let you know once per second, every second). It all depends on what you need to do.

The '328 has three timers, each with somewhat unique capabilities. TC0 and TC2 are 8-bit while TC1 is 16-bit. They provide a wealth of features that we won't go into in detail.

This guide was first published on May 29, 2018. It was last updated on Mar 08, 2024.

This page (Timers/Counters) was last updated on Mar 08, 2024.

Text editor powered by tinymce.