用51單片機(jī)定時(shí)器的應(yīng)用
#include
#define uint unsigned int
#define uchar unsigned char
sbit p23=P2^3;
uint frq,flag;
void main()
{
TMOD=0x11;
frq=50000;
flag=0;
TH0=(65536-frq)/256;
TL0=(65536-frq)%256; //開(kāi)始定時(shí)為50Ms
TH1=(65536-50000)/256;
TL1=(65536-50000)%256; //定時(shí)50ms
EA=1;ET0=1;ET1=1;
TR0=1;TR1=1;
while(1);
}
void timer0() interrupt 1
{
uchar varfor1hz;
TR0=0;
TH0=(65536-frq)/256;
TL0=(65536-frq)%256;
varfor1hz++;
if(flag<=80 )
{
if( varfor1hz==10)
{
frq=50000;
p23=!p23;
varfor1hz=0;
} //4s1HZ方波
}
if(flag>80 && flag <=160)
{
frq=50000;
varfor1hz=0;
p23=!p23;
} //4s 10HZ
if(flag>160 && flag <=240)
{
frq=10000;
varfor1hz=0;
p23=!p23;
} //4s 50HZ
if(flag>240 && flag <=320)
{
frq=5000;
varfor1hz=0;
p23=!p23;
}//4s 100HZ
if(flag>320 && flag <=360)
{
frq=2500;
varfor1hz=0;
p23=!p23;
} //4s 200HZ
if(flag>360 && flag <=480)
{
frq=1250;
varfor1hz=0;
p23=!p23;
}
if(flag>480 && flag <=560)
{
frq=625;
varfor1hz=0;
p23=!p23;
}
if(flag>560 && flag <=640)
{
frq=500;
varfor1hz=0;
p23=!p23;
}
TR0=1;
}
void timer1() interrupt 3
{
TH1=(65536-50000)/256;
TL1=(65536-50000)%256;
flag++;
if(flag==640)
{
flag=0;
frq=50000;
}
}
上面程序應(yīng)注意的是: 進(jìn)定時(shí)器中斷0后先把定時(shí)器0中斷關(guān)閉,防止內(nèi)部程序過(guò)多而造成中斷丟失;因?yàn)檫@樣是中斷控制中斷,容易出錯(cuò)誤;所以要進(jìn)入中斷0后,關(guān)中斷;
評(píng)論