TCC2 Prescaler problem

Hi Everyone,

First post here !
Working on a project where I’m using the 3 timers TCC0, TCC1 and TCC2, changing both their frequencies and duty cycles (with a rotary encoder).

Im having a strange behavior with TCC2. Because it is only 16 bits and I want to get the best possible fequency resolution, I’m updating the Prescaler depending on the desired output frequency.
But by doing so, the whole behavior of the Timer goes wrong, that is, its frequency becomes something completly unexpected.

I created separate functions for :

  • Timer init
  • setting the Prescaler
  • setting frequency and duty

When i first set the PS and frequency in the init, everything is fine, but as soon as I call once more those fuctions, I start to get wrong frequency values…

Any help would be greatly appreciated,
Thanks in advance,

Timer_TCC2_test2.ino (9.65 KB)

Hi Clement,

I had a look at your code. The reason why the frequency is going awry, is that in your setPrescaler() function you're doing a read-modify-write operation on the CTRLA register:


However, this is simply bitwise ORing the required value with the previous value of the CTRLA register.

Just remove the bitwise OR and the old value in the CTRLA register will be overwritten:


Hi Martin,

Thanks a lot for the quick answer,
This just solved my problem!
Need to work on my bitwise operators :slight_smile:
Thanks again !