Changing timer frequency on the fly

Dear Community,

I need to use timers with variable frequency for reasons that are not relevant here.
In order to save CPU, I rather change the timer frequency during runtime, than use a high-value fixed frequency and use counters inside the ISR to demultiply the actual frequency of executing code inside said ISR.
This works, with one notable downside: when changing the timer frequency, I get seldom pauses of the timer (up to 1 second) right after changing the freq.
This occurs in average one out of 20 times I change the freq - but can happen 2 times in a row, or not at all in 100 freq changes. So it's not deterministic.
I use the folowing code to change the timer freq (taking timer1 as example):

            TCCR1A = 0;  TCCR1B = 0;   TCNT1 = 0;   // Clear Timer1 control registers
            TCCR1B = (1 << WGM12) | (1 << CS12);  // CTC mode, prescaler of 256
            OCR1A = F_CPU / 256 / frequency - 1;    // Set the compare match value
            TIMSK1 = (1 << OCIE1A);                           // Enable Timer1 compare match A interrupt

frequency value range is not producing an overflow to OCR1A.

Any idea why this happens? Thanks in advance.

As a thought experiment, try and figure out what happens if the value of TCNT1 is greater than what you set OCR1A to.

Try setting TCNT1 to 0 right after setting OCR1A and seeing what happens.

1 Like

Setting TCNTn to 0 right after (instead of before) setting the new value to OCRnA seems to have solved it - the timer didn't paused during latest experiments.
HUGE THANKS!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.