#include <AT89X52.H>
unsigned char code dispbit[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f}; //P2的掃描位
unsigned char code dispcode[]={0x3f,0x06,0x5b,0x4f,0x66,
0x6d,0x7d,0x07,0x7f,0x6f,0x00,0x40}; //數碼管的字形編碼
unsigned char dispbuf[8]={0,0,0,0,0,0,10,10}; //初始化顯示值
unsigned char temp[8]; //存放顯示的數據
unsigned char dispcount; //顯示計數器值
unsigned char T0count; //T0的計數器值
unsigned char timecount; //計時計數器值
bit flag; //標志位
unsigned long x; //頻率值
//頻率計算函數
void HzCal(void)
{
unsigned char i;
x=T0count*65536+TH0*256+TL0; //得到T0的16位計數器值
for(i=0;i<8;i++)
{
temp[i]=0;
}
i=0;
while(x/10) //拆分
{
temp[i]=x%10;
x=x/10;
i++;
}
temp[i]=x;
for(i=0;i<6;i++) //換算為顯示數據
{
dispbuf[i]=temp[i];
}
timecount=0;
T0count=0;
}
void main(void)
{
TMOD=0x15; //設置定時器工作方式
TH0=0;
TL0=0;
TH1=(65536-5000)/256;
TL1=(65536-5000)%256; //初始化T1
TR1=1;
TR0=1;
ET0=1;
ET1=1;
EA=1; //開中斷
while(1)
{
if(flag==1)
{
flag=0;
HzCal(); //頻率計算函數
TH0=0;
TL0=0;
TR0=1;
}
}
}
//定時器T0中斷服務子函數
void t0(void) interrupt 1 using 0
{
T0count++;
}
//定時器T1中斷服務子函數
void t1(void) interrupt 3 using 0
{
TH1=(65536-5000)/256;
TL1=(65536-5000)%256; //初始化T1預裝值,1ms定時
timecount++; //掃描
if(timecount==200) //秒定時
{
TR0=0; //啟動T0
timecount=0;
flag=1;
}
P2=0xff; //初始化選擇引腳
P0=dispcode[dispbuf[dispcount]]; //輸出待顯示數據
P2=dispbit[dispcount];
dispcount++; //切換到下一個選擇引腳
if(dispcount==8) //如果已經掃描完成切換
{
dispcount=0;
}
}
復
|