PWM Signal Question

I am trying to create a clear PWM signal. However, for every 8 cycles, there is 1 cycle does not follow the duty cycle. How can I fix it? Please help.

Here is the code:

#include <xc.h>             /* contains Vector Name/Number Macros */
#include <sys/attribs.h>    /* contains __ISR() Macros */
#include <stdio.h>

void setup()
 pinMode(11, OUTPUT);

void loop()
 digitalWrite(11, HIGH);
 delayMicroseconds(5); // Approximately 10% duty cycle @ 1KHz
 digitalWrite(11, LOW);

 int dutyvalue = getdutyvalue();

 Serial.print("duty value "); // Display "A2 = "
 Serial.println(dutyvalue); // Display measured A2 volts


int getdutyvalue()
return analogRead(A0);


void Initialize_Timer2(){
       T2CONbits.TON = 0;
       T2CONbits.TCKPS = 8; // prescale by 256
       PR2 = 100; // setting the period of TMR2. it counts to 100 then resets.
       TMR2 = 0; // initialize timer
       T2CONbits.ON =1;

   //return 0;
void Initialize_output_compare_4(int D){
   OC4CONbits.OCM =6;  // pwm mode with no fault protection
   OC4R = D;     // value to be compared with TMR2
   OC4RS = D; //  define the duty cycle
   OC4CONbits.ON=1; // will turn on OC2 module     

Please POST your code and tell us what "messed up" means.

What board is that for? It's not an 8-bit AVR, that's for sure...

It's also not a valid arduino sketch because it's missing setup().

At high frequency, for every 8 cycles, there is 1 cycle does not follow the duty cycle.

Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.,148850.0.html then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

What is the model of the Arduino controller you are using please?

What is the application that need that PWM frequency?

Thanks… Tom… :slight_smile:

surely its a hoax
its mplabx XC8 code for a PIC micro with a few Arduino looking statements pasted in


I have a question on how to generate a PWM signal using output compare with PIC32 microcontroller Arduino based. Please help. Thank you.

@wsullin, please do not cross-post. Threads merged.