固定占空比PWM頻率可調(diào)子程序
//spdval=255 頻率=11.71875KHz
//spdval=14 頻率=200.0KHz
void HiSpd(unsigned char spdval)
{
unsigned char x;
unsigned int y;
x=PR2;
if(spdval==x) return;
if(spdval<14) //
spdval=14; //最大限定在200KHz
T2CKPS1=0;
T2CKPS0=0; //預(yù)分頻1:1
/*
y=(spdval+1)*5/2; //(CCPR1L:CCP1CON<5:4>)=(PR2+1)/占空比
if(0x0001==(y&0x0001))
{CCP2Y=1;}
else
{CCP2Y=0;}
if(0x0002==(y&0x0002))
{CCP2X=1;}
else
{CCP2X=0;}
CCPR2L=y>>2;
TMR2IF=0;
while(!TMR2IF);
PR2=spdval;
*/
if(spdval>x)
{
for(;x
{
y=(x+1)*5/2; //(CCPR1L:CCP1CON<5:4>)=(PR2+1)/占空比
if(0x0001==(y&0x0001))
{CCP2Y=1;}
else
{CCP2Y=0;}
if(0x0002==(y&0x0002))
{CCP2X=1;}
else
{CCP2X=0;}
CCPR2L=y>>2;
TMR2IF=0;
while(!TMR2IF);
PR2=x;
if((30<=x)&&(x<60))
{
delaynms(10);
}
else if((24<=x)&&(x<30))
{
delaynms(30);
}
else if((19<=x)&&(x<24))//120KHz~150KHz
{
delaynms(35);
}
else if((14<=x)&&(x<19))//150KHz~200KHz
{
delaynms(40);
}
else
{}
}
}
else
{
for(;x>=spdval;x--)
{
y=(x+1)*5/2; //(CCPR1L:CCP1CON<5:4>)=(PR2+1)/占空比
if(0x0001==(y&0x0001))
{CCP2Y=1;}
else
{CCP2Y=0;}
if(0x0002==(y&0x0002))
{CCP2X=1;}
else
{CCP2X=0;}
CCPR2L=y>>2;
TMR2IF=0;
while(!TMR2IF);
PR2=x;
if((30<=x)&&(x<60))
{
delaynms(10);
}
else if((24<=x)&&(x<30))
{
delaynms(30);
}
else if((19<=x)&&(x<24))
{
delaynms(35);
}
else if((14<=x)&&(x<19))//150KHz~200KHz
{
delaynms(40);
}
else
{}
}
}
}
//spdval=255 頻率=732.42Hz
//spdval=15 頻率=11.71875KHz
void LoSpd(unsigned char spdval)
{
unsigned char x;
unsigned int y;
x=PR2;
if(spdval==x) return;
if(spdval<15) //
spdval=15; //最大限定在11.71875KHz
T2CKPS1=1;
T2CKPS0=0; //預(yù)分頻1:16
/*
y=(spdval+1)*5/2; //(CCPR1L:CCP1CON<5:4>)=(PR2+1)/占空比
if(0x0001==(y&0x0001))
{CCP2Y=1;}
else
{CCP2Y=0;}
if(0x0002==(y&0x0002))
{CCP2X=1;}
else
{CCP2X=0;}
CCPR2L=y>>2;
TMR2IF=0;
while(!TMR2IF);
PR2=spdval;
*/
if(spdval>x)
{
for(;x
{
y=(x+1)*5/2; //(CCPR1L:CCP1CON<5:4>)=(PR2+1)/占空比
if(0x0001==(y&0x0001))
{CCP2Y=1;}
else
{CCP2Y=0;}
if(0x0002==(y&0x0002))
{CCP2X=1;}
else
{CCP2X=0;}
CCPR2L=y>>2;
TMR2IF=0;
while(!TMR2IF);
PR2=x;
if((30<=x)&&(x<60))
{
delaynms(10);
}
else if((15<=x)&&(x<30))
{
delaynms(15);
}
else
{}
}
}
else
{
for(;x>=spdval;x--)
{
y=(x+1)*5/2; //(CCPR1L:CCP1CON<5:4>)=(PR2+1)/占空比
if(0x0001==(y&0x0001))
{CCP2Y=1;}
else
{CCP2Y=0;}
if(0x0002==(y&0x0002))
{CCP2X=1;}
else
{CCP2X=0;}
CCPR2L=y>>2;
TMR2IF=0;
while(!TMR2IF);
PR2=x;
if((30<=x)&&(x<60))
{
delaynms(10);
}
else if((15<=x)&&(x<30))
{
delaynms(15);
}
else
{}
}
}
}
評(píng)論