I have a problem about phase reverse by Timer2 in 8MHz Meag128L.
I want to generate a 40KHz square wave and sometimes reverse its phase, for example, the waveform can be like:
bold area is the phase shift, and I want this phase reverse happened at any time, which means it can either be 010010 or 101101. Every 1 and 0 are 200 clock cycles for 8MHz crystal.
My old method for this problem is set Timer2 in CTC mode and set OCR2 = 199, which is 40KHz and toggle OC2. and in CTC interrupt, I always use a variable to remember the output value of OC2, because when I want to do the phase reverse, I have to know the current value of OC2 and then set PORTB7 to that value and then disconnect OC2, and in the next CTC interrupt I connect OC2 again to let it toggle, so that I can have a 180 degree of phase shift.
But the problem with this method is it comsum too many calculation resources. Every 200 system clock cycles I will run this interrupt once and it take at least 15 clock cycles to finish and jump back, it's just too much for doing such a small thing.
So can you tell me some better way to do it so that it can use less calculation power?