//用定時計數(shù)器0作為脈沖計數(shù)器,定時器1作為定時器用,定時50ms產(chǎn)生中斷
//中斷10次后(即0.5s)讀計數(shù)器0的數(shù)據(jù)乘2即為所得頻率值,適于頻率變化較慢的場所
//先進行50ms預(yù)判斷,若TH0計數(shù)值大于12,說明1S內(nèi)計數(shù)值將超過65535(雖0.5S內(nèi)遠不超65535)
//變量ee是無符號整數(shù)不能超過65535,為防止出錯,則報警
//最大可測頻率約65535hz,實際上STC12C系列是1T單片機,11.0592下其最高可計數(shù)頻率遠大于此
#include <reg52.h>
#include <math.h>
#define uint unsigned int
#define uchar unsigned char
//定義以I/O口的功能
sbit beiguang=P3^2;//液晶屏背光
sbit rs=P1^3;//液晶屏寫選擇,0命令 1數(shù)據(jù)
sbit rw=P1^4;//液晶屏讀寫選擇
sbit lcden=P1^5;//液晶屏使能
sbit fm=P1^7;//蜂鳴器
#define db P2 //定義P2為數(shù)據(jù)輸出口,寫數(shù)據(jù)時用db代替P2,增加液晶屏程序的通用性
//更改硬件接線時,只更改此處,而不必去更改液晶屏讀寫子程序
uchar aa,bb,cc;
uint dd,ee;
void Delay1ms(unsigned int i) //1ms延時程序
{
unsigned int j;
for(;i>0;i--)
{
for(j=0;j<125;j++)
{;}
}
}
void init()//初始化設(shè)置
{
TMOD=0x15;//定時器0作為計數(shù)器,定時器1作為定時器用
TH0=0;//計數(shù)器清0
TL0=0;
EA=1;//開總中斷
ET1=1;//允許定時器1中斷
TH1=0x4c;
TL1=0x5c;
TR0=1;//啟動計數(shù)器
TR1=1;//啟動定時器
aa=0;
}
void write_com(uchar com)//向液晶屏寫命令
{
db=com;
rs=0;
rw = 0;
lcden=0;
Delay1ms(10*12);
lcden=1;
Delay1ms(10*12);
lcden=0;
}
void write_date(uchar date)//向液晶屏寫數(shù)據(jù)
{
db=date;
rs=1;
rw = 0;
lcden=0;
Delay1ms(10*12);
lcden=1;
Delay1ms(10*12);
lcden=0;
}
void init2()//液晶屏初始化
{
beiguang=0;
rw=0;
write_com(0x38);//顯示模式16字*2行,5*7點陣,數(shù)據(jù)口8位
Delay1ms(10*12);
write_com(0x0f);//開顯示,顯示光標,光標閃爍
Delay1ms(10*12);
write_com(0x06);//寫完數(shù)據(jù)后數(shù)據(jù)指針和光標位置自動加1
Delay1ms(10*12);
write_com(0x01);//屏幕清除
Delay1ms(10*12);
}
void display4(unsigned int number) //單行多位顯示程序
{
uchar A1,A2,A3,A4,A5;
init2();//液晶屏初始化
A1=number/10000%10;//分離出十萬,萬,千,百,十,個
A2=number/1000%10;
A3=number/100%10;
A4=number/10%10;
A5=number%10;
write_com(0x80);//第1個數(shù)據(jù)的位置設(shè)定,第1行第1列
Delay1ms(10);
write_date(0x30+A1);//寫數(shù)據(jù)
Delay1ms(10);
write_date(0x30+A2);
Delay1ms(10);
write_date(0x30+A3);
Delay1ms(10);
write_date(0x30+A4);
Delay1ms(10);
write_date(0x30+A5);
Delay1ms(10);
write_com(0x87);//第6個數(shù)據(jù)'H'的位置,中間空85和86 二格
write_date('H');
Delay1ms(10);
write_date('z');
Delay1ms(10);
}
void main()//主程序很簡單
{
init();//初始化
while(1)//循環(huán)程序
{
dd=bb*256+cc;//0.5S的計數(shù)值
ee=2*dd;//換算為1秒鐘的計數(shù)值
if(aa==1)
{
if(TH0>12)//預(yù)判斷,50ms內(nèi)TH0>12,1s內(nèi)計數(shù)值將超過可計數(shù)的最大值65535
fm=1;//報警
}
display4(ee);//顯示
fm=0;//報警停止
}
}
void timer1()interrupt 3//注意:定時器1的中斷序號為3
{
aa++;
TH1=0x4c;//11.0592Mhz
TL1=0x5c;//實際電路振蕩頻率11.03705Mhz,對TL1修正
if(aa==10)//中斷10次,共0.5S
{
TR0=0;//暫停計數(shù)
aa=0;
bb=TH0;//讀出計數(shù)器數(shù)據(jù)
cc=TL0;
TL0=0;//計數(shù)器清0
TH0=0;
TR0=1;//重新啟動計數(shù)器
}
}
|