Phase and frequency correct PWM mode Arduino Mega 2560
You wrote:


  TIMSK4 |= (1&lt;&lt;OCIE4A);


and then never defined ISR(TIMER4_COMPA_vect). As soon as you get a
compare match, you get a bad interrupt, which defaults to resetting your
program and restarting again from reset vector.