## Dean Camera's Timer tutorial question

4 posts / 0 new
Author
Message

Can someone please explain why Dean says we need to decrement the number of ticks by one?  I'm not seeing the logic in his argument.

The only reason I can see to decrement the number of ticks is because of the timer resetting uses one cycle?  So, in his example 50,000 ticks is 1/20th of a second.  Decrement by 1 = 49999.  Timer counts down to 0 then the next clock cycle tick would be "wasted" or spent resetting to 49999?  And how important is that one cycle?  I was under the impression that the internal clocks are a poor time keeper prone to significant error.  Maybe on an 8 bit timer it might be a little more important?

The AVR timers will only update their count on each timer input clock tick, thus it takes one tick
to get from a count of zero to one, or from the timer's maximum value back to zero. As a result,
we need to decrement the number of ticks in our calulation by one as shown in the above formula.

Since the count begins at 0, you count to N-1 to get N counts.

For example, a count of 5 would be 0, 1, 2, 3, 4.

You are correct in that often the internal clocks may not be extremely accurate; however, the number of counts may be important for more than just timing accuracy.

David (aka frog_jr)

I was under the impression that the internal clocks are a poor time keeper prone to significant error.

You're probably thinking of the internal oscillator.  This is not the same thing as the internal timer peripherals.  Those timers are cycle-accurate.  The internal oscillator, if used to clock the AVR, will of course also clock the timers, so they will only have as good an absolute accuracy of the internal oscillator in that case.  However, w.r.t. the cpu, also running from the same clock source, the timers will still be cycle-accurate.

As frog_jr has said, your take away one because timer counting is zero-based.  Same as you would with any other zero-based count, like an array in C.  An array declared as foo[5] is five elements long:  foo[0], foo[1], foo[2], foo[3], and foo[4].

 "Experience is what enables you to recognise a mistake the second time you make it." "Good judgement comes from experience.  Experience comes from bad judgement." "Wisdom is always wont to arrive late, and to be a little approximate on first possession." "When you hear hoofbeats, think horses, not unicorns." "Fast.  Cheap.  Good.  Pick two." "We see a lot of arses on handlebars around here." - [J Ekdahl]