Datasheet
Chapter 12.
39
Pulse Width Modulation
// Set up timer 2 for PWM
TMR2 = 0; // Clear timer 2
PR2 = 1000; // Timer 2 counter to 1000
T2CON = 0x8010; // Fosc/4, 1:4 prescale, start TMR2
// Set up PWM on OC2 (RD1)
OC2RS = 1024; // PWM 2 duty cycle
OC2R = 0; //
OC2CON = 0x6; // Set OC2 to PWM mode, timer 2
// Loop through 360 degrees
for ( theta=0.0; theta<TWOPI; theta += 0.05 )
{
// Set the brightness of the LED based on the sine
// of the angle.
OC2RS = (int)(512.0-512.0*sin(theta+PIOVER4));
// Slow it down
for ( i=0; i<50000; i++ )
;
}