利用51单片机实现频率测量
利用51单片机定时器实现频率测量,不同单片机晶振不同,实际使用按实际单片机晶振频率求计数器初值。
#include "reg52.h"
#define _capacity 40 //计40次
typedef unsigned char u8;
typedef unsigned int u16;
typedef unsigned long int u32;
sbit LSA = P2 ^ 2;
sbit LSB = P2 ^ 3;
sbit LSC = P2 ^ 4;
sbit test = P1 ^ 0;
void Delay(u16 i) //i=1时,大约延时10us
{
while (i--);
}
void PositionSele(u8 a, u8 b, u8 c)
{
LSA = a; LSB = b; LSC = c;
Delay(100);
}
u32 Sum(u16* first, u16* last)
{
u32 _value = 0;
for (; first != last; ++first)
_value = _value + *first;
return _value;
}
void TimerTnit()
{
TMOD = 0x15; //定时器1定时,T0计数,模式1
TH1 = 0x9E; //25ms
TL1 = 0x58;
EA = 1;
ET1 = 1;
TR1 = 1;
TR0 = 1;
}
u8 count_times = 0;
u16 count[_capacity];
void Timer1() interrupt 3
{
TR0 = TR1 = 0;
count[count_times++] = (TH0 << 8) | TL0;
TH0 = TL0 = 0;
TH1 = 0x9E;
TL1 = 0x58;
TR0 = TR1 = 1;
test = ~test;
}
u8 code segment_code[10] = { 0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
0x7f,0x6f }; //显示0~9的值
void DigDisplay(u8 val)
{
P0 = segment_code[val / 100000 % 10]; //发送段码
PositionSele(1, 1, 1);
P0 = segment_code[val / 10000 % 10];
PositionSele(0, 1, 1);
P0 = segment_code[val / 1000 % 10];
PositionSele(1, 0, 1);
P0 = segment_code[val / 100 % 10];
PositionSele(0, 0, 1);
P0 = segment_code[val / 10 % 10];
PositionSele(1, 1, 0);
P0 = segment_code[val % 10];
PositionSele(0, 1, 0);
}
void main()
{
u32 value = 0;
TimerTnit();
while (1)
{
if (count_times == _capacity)
{
TR0 = TR1 = 0;
value = Sum(count, &count[_capacity]);
count_times = 0;
TR0 = TR1 = 1;
}
DigDisplay(value);
}
}
前行