void PWM_Init(void)
{
PR2=0x67; //period for 12kHz
TRISCbits.TRISC2=0;
TRISCbits.TRISC1=0;
T2CON = 0x01;
CCP1CON =0x0F; // PWM mode enabled and duty ratio bits are set to 0
CCP2CON =0x0F;
T2CONbits.TMR2ON =1;
}
void getdutyratio(unsigned int x)
{
unsigned int lsb=0,msb=0;
long int a;
MAXDUTY = (_XTAL_FREQ/(PWMFREQ*TMR2PRESCALE));
a = ((float)x*MAXDUTY)/1023;
//a=x;
lsb = a>>2;//a&0x03FC;
//lsb=lsb>>2;
msb = a&0x0003;
CCPR1L=lsb;
msb = msb<<4;
CCP1CON&= 0xCF;
CCP1CON|=msb;
}
int sinetable[61]={0,10,20,31,41,52,62,72,83,93,103,113,123,133,143,153,162,172,181,190,200,208,
217,226,235,243,251,259,267,275,282,290,297,304,310,317,323,329,335,341,346,
351,356,361,365,369,373,377,380,383,386,388,391,393,395,396,397,398,399,399,400};
void interrupt T1_ISR(void)
{
PIR1bits.TMR1IF=0;
TMR1L=0x97;
TMR1H=0xFF;
if(dir==1)
{
duty=sinetable[i];
i++;
if(i>60){
dir=0;
i=60;
}
}
else if(dir==0)
{
duty=sinetable[i];
i--;
if(i==0)
{ dir=1;
i=0;
}
}
getdutyratio(duty);
}