运用定时器发生PWM波调理P0和P2口VD的亮度,当按下K01时,VD亮度减小,当按下K02时,VD亮度添加,设P0和P2口低高电平灯亮,反之灯灭。
电路图:
C程序:
#include
#include
sbit K01=P1^4; //添加键
sbit K02=P1^5; //削减键
sbit BEEP=P3^7;//蜂鸣器
unsigned char PWM=0x7f;//赋初值
void Beep();
void delayms(unsigned char ms);
void delay(unsigned t);
void main()
{
P0=0xff;
P1=0xff;
P2=0xff;
P3=0xff;
TMOD=0x21;
TH0=0xfc;//1ms延时常数12M
TL0=0x18;//频率调理
TH1=PWM;//脉宽调理
TL1=0;
EA=1;
ET0=1;
ET1=1;
TR0=1;
while(1)
{
do{if(PWM!=0xff){PWM++;delayms(10);}
else Beep();}while(K01==0);//K01按下,亮度变暗
do{if(PWM!=0x01){PWM–;delayms(10);}
else Beep();}while(K02==0);//K02按下,亮度变亮
} }
void timer0() interrupt 1 //定时器0中止服务程序
{
TR1=0;
TH0=0xfc;
TL0=0x66;
TH1=PWM;
TR1=1;
P0=0x00;
P2=0x00; //发动输出
}
void timer1() interrupt 3//定时器1中止服务程序
{TR1=0;P0=0xff;P2=0xff;}//完毕输出
void Beep()//蜂鸣器子程序
{unsigned char i;
for(i=0;i<100;i++){delay(100);BEEP=!BEEP;}//Beep取反
BEEP=1;delayms(100);//封闭蜂鸣器,并延时
}
void delay(unsigned char t){while(t–);}//延时子程序1
void delayms(unsigned char ms)//延时子程序2
{unsigned char i; while(ms–){for(i=0;i<120;i++);}}