标题:
单片机周频法测频率计
[打印本页]
作者:
柳柳爱喝茶
时间:
2018-7-16 10:28
标题:
单片机周频法测频率计
#include "reg52.h"
#define uint unsigned int
#define uchar unsigned char
#define ulong unsigned long
sfr AUXR=0x8E;
sfr T2H=0xD6;
sfr T2L=0xD7;
sfr IE2=0xAF;
bit flag=0,new=0,old=1;
uchar code DM[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xff};
uchar code WM[]={0x01,0x02,0x04,0x8,0x10,0x20,0x40,0x80};
uchar buf[8],num,num0=0;
ulong g_time,time;
ulong nhz,all,nhz0;
ulong buf0[4]={0};
double nhz1;
void SEL_INIT()
{
P2=(P2&0x1f)|0x80;
P0=0xff;
P2=(P2&0x1f)|0xa0;
P0=0x00;
P2 &=0x1f;
}
void T0_ISR() interrupt 1
{
static uchar i=0;
if(flag==0)
{
TH0=0xff;
TL0=0xff;
if(i==5)
{
TH1=0;
TL1=0;
TR1=1;
ET1=1;
num0=0;
}
if(i==6)
{
time=num0*65536+256*TH1+TL1;
nhz1=1000000000/time;
nhz1 =nhz1*1.01908;
nhz=nhz0=(ulong)nhz1;
nhz /=1000;
TR1=0;
ET1=0;
TH1=0;
TL1=0;
num0=0;
}
if(++i>9) i=0;
}
else num++;
}
void T1_ISR()interrupt 3
{
num0++;
}
void T2_ISR() interrupt 12
{
static uchar k,i=0;
char j=7,l;
P2=(P2&0x1f)|0xc0;
P0=0x00;
P2=(P2&0x1f)|0xe0;
if(flag==0&&i==4)
P0=DM[buf[i]]&0x7f;
else
P0=DM[buf[i]];
P2=(P2&0x1f)|0xc0;
P0=WM[i];
if(++i>7) i=0;
if(++g_time>499)
{
if(flag)
{
nhz=num*65536+256*TH0+TL0;
nhz *=1.00176;
TR0=0;
TH0=0;
TL0=0;
num=0;
nhz0=nhz;
}
buf0[k]=nhz0;
if(++k>2) k=0;
all=0;
for(l=0;l<3;l++) all +=buf0[l];
nhz0=all/3;
while(nhz0)
{
buf[j--]=nhz0%10;
nhz0 /=10;
}
for(;j>-1;j--) buf[j]=0;
g_time=0;
if(flag) TR0=1;
}
}
void T_INIT()
{
TMOD=0x15;
TH0=0xff;
TL0=0xff;
TL1=0x00;
TH1=0x00;
ET0=1;
TR0=1;
AUXR &= 0xFB; //定时器时钟12T模式
T2L = 0x30; //设置定时初值
T2H = 0xF8; //设置定时初值
AUXR |= 0x10; //定时器2开始计时
IE2 |=0x04;
EA=1;
}
void main()
{
SEL_INIT();
T_INIT();
while(1)
{
if(nhz<2000) flag=0;
else flag=1;
new=flag;
if(new!=old)
{
old=new;
if(flag) //1测频
{
TH0=0;
TL0=0;
}
else //0测周
{
TH0=0xff;
TL0=0xfe;
TL1=0x00;
TH1=0x00;
num0=0;
}
}
}
}
复制代码
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1