1.1 Configuring the PWM Module

PWM and Timer2 Initialization Routines shows how to configure a standard 10-bit PWM. The example includes the initialization routines for the PWM and Timer2 modules, both of which are necessary to generate a PWM signal.

PWM and Timer2 Initialization Routines

void PWM3_Initialize(void)
 {
    PWM3CON = 0x80;                              // POL active_hi; EN enabled
    PWM3DCH = 0x27;                              // DC = 50%
    PWM3DCL = 0xC0;
 }

 void PWM3_LoadDutyValue(uint16_t dutyValue)
 {
     PWM3DCH = (dutyValue & 0x03FC)>>2;         // 8 MSBs of PWM duty cycle
     PWM3DCL = (dutyValue & 0x0003)<<6;         // 2 LSBs of PWM duty cycle
 }

 void TMR2_Initialize(void)
 {
    T2CLKCON = 0x01;                           // T2CS FOSC/4
    T2HLT = 0x00;
    T2RST = 0x00;
    T2PR = 0x4F;                               // Rollover every 10 us
    T2TMR = 0x00;    
    PIR4bits.TMR2IF = 0;                       // Clear IF flag
    T2CON = 0x80;                              // CKPS 1:1; OUTPS 1:1; ON on
 }