0

I'm trying to learn how to use the CTC mode in AVR and I'm trying to figure out why I should minus 1 when I set the comparing value. For instance,now I'm working to send the working time of the AVR every 200 ms and with the calculation I find out the value should be 50000,however in a video about this program,the man claims that it should be 50000-1,why is that?

Athar
  • 963
  • 10
  • 23
Lep Li
  • 3
  • 2

1 Answers1

0

It's because the underlying counter starts at zero and ends at "TOP" as it's referred to in the various AVR datasheets. Without know the exact part you're using, I can't refer you to a datasheet, but they all use basically the same terminology in their matrix of timer modes.

So if you want the counter to count exactly 50000 times, you have to subtract one. CTC means "timer on compare match" and starting at zero means you need to be "off by one." Simple as that.

Really good discussion of this and other AVR topics at AVRGeeks

TomServo
  • 7,248
  • 5
  • 30
  • 47
  • Thanks,but does "starting at zero" mean that when the counter counts one ,it reaches zero and when it counts 50000 times,it reaches 49999? So the iniatIal value of the timer is actually -1? For example,if I want to count once,I simply should set the TOP value as 0? – Lep Li Oct 15 '20 at 16:39
  • @LepLi you should consult the datasheet for the exact part you're using. But the convention is as I mentioned. This is common in other microcontrollers also -- the STM32 family is just the same (except having a larger range of prescalers from which to choose). – TomServo Oct 15 '20 at 17:26
  • Huge thanks for your help anyway and I think I now know the reason behind all of this,simple indeed.@TomServo – Lep Li Oct 15 '20 at 17:59
  • @LepLi You're welcome; showing your thanks by accepting and upvoting the answer will allow others to benefit from it as well. – TomServo Oct 15 '20 at 20:46