user57907: 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() {
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);

TCCR4A=0;
TCCR4B=0;
//Timer 1 1kHz mode 8: phase and frequency correct pwm oc1a non inverting

TCCR4A=(1<<COM4A1)|(0<<COM4A0)|(0<<WGM41) ;//| (0<<WGM40)
TCCR4B=(1<<WGM43)|(0<<WGM42);//
ICR4=b;
OCR4A=int(b*1/5);
TCCR4B|=(1<<CS10);
TIMSK4 |=(1<<OCIE4A);
}

void loop() {
  } 

ISR(TIMER_COMPA_vect){

  }   

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

Duty cycle:0.2 (OCR4A=b/2)

user7508: 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.

57907: <p>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?
</p>

<pre class="lang-cpp prettyprint-override"><code>unsigned int b=7999;
void setup() {
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);

TCCR4A=0;
TCCR4B=0;
//Timer 1 1kHz mode 8: phase and frequency correct pwm oc1a non inverting

TCCR4A=(1&lt;&lt;COM4A1)|(0&lt;&lt;COM4A0)|(0&lt;&lt;WGM41) ;//| (0&lt;&lt;WGM40)
TCCR4B=(1&lt;&lt;WGM43)|(0&lt;&lt;WGM42);//
ICR4=b;
OCR4A=int(b*1/5);
TCCR4B|=(1&lt;&lt;CS10);
TIMSK4 |=(1&lt;&lt;OCIE4A);
}

void loop() {
  } 

ISR(TIMER_COMPA_vect){

  }   
</code></pre>

<p>The output of the code for different duty cycles are as below
<strong>Duty cycle:0.2 (OCR4A=b/5)</strong>
<a href="https://i.stack.imgur.com/VHwhd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VHwhd.png" alt="enter image description here"></a></p>

<p><strong>Duty cycle:0.2 (OCR4A=b/2)</strong><a href="https://i.stack.imgur.com/dRlOd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dRlOd.png" alt="enter image description here"></a></p>
 7508: <p>You wrote:</p>

<blockquote>
  <p><code>TIMSK4 |= (1&lt;&lt;OCIE4A);</code></p>
</blockquote>

<p>and then never defined <code>ISR(TIMER4_COMPA_vect)</code>. 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.</p>
