void set_pwm (uns16 dcycle)
{
//PWM period = [(pr2)+1]x4xToscxTMR2prescalevalue
//Set PWM period by writing to the PR2 register
//PWM Frequency -- 976Hz (PR2=0xFF Timer prescaler = 1:4 Max Res=10)
//PWM Period -- 1.025ms 
//PR2 = (1.025ms / (4x2.5x10-7x4))-1 =255.25 = 255 = 0xFF
//TMR2 Prescaler Value = 1/16
T2CON.0=1;
T2CON.1=0;
PR2=61;



//Set PWM duty cycle by writing to the CCPR1L regiser and CCP1CON<5:4> bits
//CCP1CON -- __  __  CCP1X  CCP1Y  CCP1M3  CCP1M2 CCP1M1 CCP1M0
//CCP1x CCP1y = used for PWM Duty cycle LSB 2bits 
//CCP1M.. = Mode select bits, 11xx for PWM modeb
//CCP1CON=0b00001100;

//CCPR1L contains upper 8 bits of the 10 bit dutycycle and CCP1CON<5:4> lower 2 bits of the 10bit dutycycle
//PWM dutycycle = (CCPR1L:CCP1CON<5:4>)xToscxTMR2Prescalervalue
//Set %50 of period 0.001 %50 = 0.0005
//CCPR1L:CCPR1Con<5.4> = 5.124^-4 / (2.5x10^-7x4) = 512.5 = 0b1000000000
uns16 duty_cycle_val;
duty_cycle_val=dcycle;

CCP1X=duty_cycle_val.1; //Bit 1  
CCP1Y=duty_cycle_val.0; //Bit 0

duty_cycle_val=duty_cycle_val/4;

CCPR1L=duty_cycle_val.low8;
//CCP1X=0; //Bit 1  
//CCP1Y=1; //Bit 0

//Make the CCP1 pin and output by clearing the TRISB.3
TRISB.3=0;


//T2CON -- TOUTPS3 TOUTPS2 TOUTPS1 TOUTPS0 TMR2ON T2CKPS1 T2CKPS0
//Set TMR2 prescaler value and enable TMR2 by writing T2CON
T2CON=0b00000101; //Set 1:1 prescale value and enable Time2

//Configure the CCP1 module for PWM application
CCP1CON = CCP1CON & 0b00110000;
CCP1CON = CCP1CON ^ 0b00001111;

}
