I wrote a code to generate 1kHz Phase and frequency correct PWM signal from Arduino mega 2560 using timer 4. When I try the code with fast PWM mode it works perfectly. But phase correct mode didn't provide the expected outcome. What is wrong with my code?

unsigned int b=7999;
void setup() {

//Timer 1 1kHz mode 8: phase and frequency correct pwm oc1a non inverting

TCCR4A=(1<<COM4A1)|(0<<COM4A0)|(0<<WGM41) ;//| (0<<WGM40)
TIMSK4 |=(1<<OCIE4A);

void loop() {



The output of the code for different duty cycles are as below Duty cycle:0.2 (OCR4A=b/5) enter image description here

Duty cycle:0.2 (OCR4A=b/2)enter image description here

  • see the diagrams for pwm timing in the datasheet
    – Juraj
    Jul 5, 2019 at 6:36
  • Can you please explain what is wrong Jul 5, 2019 at 6:40
  • in phase correct pwm the counter counts up and then down and so it matches the compare register twice in one period. first while counting up a second match while counting down. the pin changes state on both matches
    – Juraj
    Jul 5, 2019 at 8:04
  • That's what I need. But it's clear from the wave form that the pin trigger while down counting and resets immediately as a glitch Jul 5, 2019 at 8:36

1 Answer 1


You wrote:

TIMSK4 |= (1<<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.

  • When I added interrupt service routine (ISR(TIMER4_COMPA_vect)) the output waveform acts exactly like fast PWM. It does not provide phase correct wave Jul 5, 2019 at 13:47
  • @VivekVijayan: Do you get the expected frequency? If so, how do you tell it is not phase correct? Jul 5, 2019 at 14:19
  • @Edger Bonet: I am getting the expected frequency. But when I observe the waveform all the waves with different duty cycle starts from the same point. I believe in phase correct pwm mode the OCnA or OCnB pins are set during upcounting. So I could expect different starting points(in time) for waves with different duty cycles Jul 5, 2019 at 14:42
  • @VivekVijayan: You would not get 1 kHz in fast PWM mode. Re “different starting points (in time)”: What is your time reference for defining the starting points? Are you using an oscilloscope? If so, how did you configure its trigger? Jul 5, 2019 at 15:47
  • 1
    @VivekVijayan: Your phase correct waveform is fine. It looks wrong to you only because you don't understand how your DSO sets its time axis. Jul 5, 2019 at 16:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.