新聞中心

EEPW首頁(yè) > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > 用51單片機(jī)定時(shí)器的應(yīng)用

用51單片機(jī)定時(shí)器的應(yīng)用

作者: 時(shí)間:2016-11-18 來(lái)源:網(wǎng)絡(luò) 收藏
用51單片機(jī)定時(shí)器產(chǎn)生周期的8種不同頻率的方波;其中定時(shí)器1控制頻率時(shí)間,即每個(gè)波形4s;定時(shí)器0控制波形的頻率;

#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;
}
}

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

上面程序應(yīng)注意的是: 進(jìn)定時(shí)器中斷0后先把定時(shí)器0中斷關(guān)閉,防止內(nèi)部程序過(guò)多而造成中斷丟失;因?yàn)檫@樣是中斷控制中斷,容易出錯(cuò)誤;所以要進(jìn)入中斷0后,關(guān)中斷;



關(guān)鍵詞: 51單片機(jī)定時(shí)

評(píng)論


技術(shù)專區(qū)

關(guān)閉