单片机变频pwm实验程序设计与原理
扫描二维码
随时随地手机看文章
利用stc的一款单片机提供的PWM实现变频输出。程序将变频pwm输出到LED上作测试。
#include
sfrCCON = 0xD8;
sfr CMOD = 0xD9;
sfr CL = 0xE9;
sfr CH = 0xF9;
sfr CCAP0L = 0xEA;
sfr CCAP0H = 0xFA;
sfr CCAPM0 = 0xDA;
sfr CCAPM1 = 0xDB;
sbit CR = 0xDE;
sbit led = P2^0;
unsigned char duty = 0x80;
unsigned int fre = 0xffff;
void timer0_int (void) interrupt 1 using 1
{
TH0 = fre >> 8;
TL0 = fre & 0xff;
led = ~led;
}
void timer0_init(void)
{
TMOD &= 0xf0;/* Set timer 0 */
TMOD |= 0x1;/* mode 1 */
TH0 = 0xff;
TL0 = 0xff;
TR0 = 1;/* Enable timer 0 */
ET0 = 1;/* Enable timer 0 interrupt */
}
void pwm_init(void)
{
CMOD = 0x4; // Use timer0
CL = 0x0;
CH = 0x0;
CCAP0H = duty; //Duty Cycle
CCAPM0 = 0x42; // PWM mode
CR = 1; //Start PCA Timer.
}
voidSOFt_delay(unsigned int _1ms)
{
unsigned int tmp;
while(_1ms--!=0) {
for(tmp=0;tmp<144;tmp++);
}
}
void check_key(void)
{
unsigned char key1,key2;
key1 = P1 & 0xf;
soft_delay(20);
key2 = P1 & 0xf;
if(key1 == key2 && key1 != 0xf){
if(key1 == 0xe)
duty += 16;
else if(key1 == 0xd)
duty -= 16;
else if(key1 == 0xb)
fre += 0xff;
else if(key1 == 0x7)
fre -= 0xff;
while((P1 & 0xf) != 0xf);
}
}
void main (void)
{
pwm_init();
timer0_init();
EA= 1;
while(1){
CCAP0H = duty;
check_key();
}