4.8 PWM Mode Configuration

PWM Mode Initialization Routines shows the CCP and Timer2 Initialization routines. In this example, the CCPRx register pair is loaded with a value, 0x63, which will result in a 50% duty cycle. Timer2 is configured to generate a PWM frequency of 20 kHz.

PWM Mode Initialization Routines

void PWM1_Initialize(void)
{
    CCP1CON = 0x8F;                // MODE PWM; EN enabled; FMT right
    CCPR1H = 0x00;                 // Set for 50% duty cycle
    CCPR1L = 0x63;
}

void TMR2_Initialize(void)
{
    T2CLKCON = 0x01;               // T2CS FOSC/4
    T2HLT = 0x00;
    T2RST = 0x00;
    T2PR = 0x31;                   // Set PWM Period
    T2TMR = 0x00;
    PIR1bits.TMR2IF = 0;           // Clear IF flag
    T2CON = 0x80;                  // T2CKPS 1:1; T2OUTPS 1:1; TMR2ON on
}