新聞中心

EEPW首頁(yè) > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 固定占空比PWM頻率可調(diào)子程序

固定占空比PWM頻率可調(diào)子程序

作者: 時(shí)間:2016-11-11 來(lái)源:網(wǎng)絡(luò) 收藏
//PWM頻率=1/((PR2+1)*4*(1/fosc)*預(yù)分頻值)HZ

//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
{}
}
}
}

本文引用地址:http://m.butianyuan.cn/article/201611/316736.htm


評(píng)論


技術(shù)專(zhuān)區(qū)

關(guān)閉