phase shift with variable frequency

hello friends.i have question about shifting pwm outputs on mega2560. uploaded code does 2 shifted output signal one from each other for 1 second.i set 2 phase and frequency correct mode for 2 timers,TCNT3 value is TOP-15625.My question is ho to make stable shift for variable frequency?because if i try to regulate OCR4A,OCR3A and TCNT3,it goes out of shift.Guys do u have any idea what should be best?this code is just simple for testing, im trying to figure out phase shift for 3 timers but here we can understand it better.

void setup() {
DDRH |= (1<<PH3) | (1<<PH4) | (1<<PH5)  ; 
DDRE |= (1<<PE3) | (1<<PE4) | (1<<PE5) ;   //outputs 678-timer4,235-timer3
TCCR3A = 0<<COM3A1 | 1<<COM3A0 | 1<<COM3B1 | 0<<COM3B0 | 1<<COM3C1 | 1<<COM3C0 
        | 0<<WGM31 | 1<<WGM30 ;   
TCCR3B = 1<<WGM33 | 0<<WGM32 | 1<<CS32 | 0<<CS31 | 1<<CS30 ;

TCCR4A = 0<<COM4A1 | 1<<COM4A0 | 1<<COM4B1 | 0<<COM4B0 | 1<<COM4C1 | 1<<COM4C0 
        | 0<<WGM41 | 1<<WGM40 ;
TCCR4B = 1<<WGM43 | 0<<WGM42 | 1<<CS42 | 0<<CS41 | 1<<CS40 ;
// phase and freq correct COMnA-top, COMnB- output noninverter COMnC-unused inverter output
// prescaler /1024
GTCCR = (1<<TSM)|(1<<PSRASY)|(1<<PSRSYNC);  //stopping timer counting 
TCNT3=49910;    //setting timer3 to start count from this value
TCNT4=0;            // TOP-OCR4/3A =tcnt3 or 0-OCR3/4A this make shift 
GTCCR = 0;   //release timers
}
void loop() {

OCR4A=OCR3A=15625;   //0,5 hz TOP value 
OCR3B=OCR3A/2;           // 1hz output alternating switching OCR3B and OCR4B
OCR4B=OCR4A/2;
}

But to much work to reverse engineer it all, but did you use the same timer for the shifted PWM and did you use the "Phase and frequency correct"-mode?

i know its simply can be done by inerting or CTC mode on 1 timer but my main project requires 3 shifted timer one from each other and here im trying to figure it out and trying how to make it possible :smiley: so the question is how to make stable phase shift of 2 timers with varying frequency?

Mm, some uC's can do that in hardware but non of the default Arduino's I know. So yeah, it get's a lot more complicated...

But I'm not going to reverse engineer your code to see if you're on the right track. Comments would be a good start :slight_smile:

im afraid you re right, looks like shifting timers at stable frequency is pretty simple but vhen its varyied, i think it goes out of shift because its different updating of OCRn and TCNT.but isnt any way to do it?