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.