Force TCNT to stay below OCRxA on ATmega328P I'm using a timer and the TIMERx_COMPA ISR to generate a signal in "the background".

This ISR is triggered when the timer reaches a certain value (OCRxA), which in turn can be changed by the user.
Once the ISR triggers, the timer is reset and the next waiting period occurs.

If the compare value (OCRxA) is changed to a value below the current timer value before having hit the old compare value, the timer keeps running until it overflows back to 0 and hits the new OCRxA value. This results in no signal being generated until the timer has looped around, which can be quite long for the 16-bit TIMER1 timer.

There are multiple way to get around this:


Reset TCNTx to zero whenever OCRxA. Easy, but one signal will always be off-clock
If TCNTx is greater than OCRxA (after changing OCRxA), reset it to just below OCRxA
If TCNTx is greater than OCRxA, trigger the interrupt manually, where the signal is generated and TCNTx is reset


I belive the third option would be the cleanest, both in checking whether the issue has occured as well as for the signal quality.

This is certainly an X -&gt; Y problem, so I'm open for other approaches.

My question, for now, would be:
Can I manually jump to an ISR regardless of its "normal" trigger?
Can I manually jump to an ISR regardless of its "normal" trigger?


This should be possible, but is probably not the best solution.


  This is certainly an X -&gt; Y problem, so I'm open for other
  approaches.


It would seem you are using the timer in CTC mode. In this mode, when
you write to OCRxA, the register is updated immediately, which leads
to the problem you are experiencing. The solution is to instead set the
timer to “fast PWM” mode. In fast PWM mode, the OCRxA register is
double buffered: you will be actually writing to a buffer register, and
OCRxA is automatically updated from that buffer on the same timer
clock cycle that clears the counter.

It may sound counter-intuitive to use a PWM mode when you do not need
the PWM feature. However, as long as the “compare output mode” is set to
“normal port operation” for both channels, the timer will not generate
any PWM output, and you can legitimately use the fast PWM mode only for
its double buffer feature.