#include "sys.h"
//#include "lcd12864.h"
sbit Trig = P1^1;
sbit Echo = P1^2;
uint cnt = 0; //时间圈数
void Timer0_Init(void)
{
/*定时器0初始化*/
TMOD |= 0x01; //选择定时器0工作 工作方式为方式1
TH0 = 0; //装初值0
TL0 = 0;
TF0 = 0; //中断溢出标志位
ET0 = 1; //开定时器中断
EA = 1; // 开总中断
}
float Distance1(void)
{
uint time_data=0;
float Distance;
uint outcomeH=0,outcomeL=0;
/* 发送20us脉冲 */
Trig = 0;
Delay10us();
Trig = 1;
Delay20us();
Trig = 0;
/* 判断是否接受到回波,接受到回波打开定时器*/
while(!Echo);
TR0 = 1;
while(Echo);
TR0 = 0;
if(cnt < 5)
{
time_data = outcomeH*256 + outcomeL ;
Distance = time_data / 58;
}
else
{
Distance = 0;
}
cnt = 0;
TH0 = TL0 = 0;
return Distance;
}
void Timer0() interrupt 1
{
cnt++;
}
主程序:
void main()
{
float uidistance = 0;
EA = 0;
Timer0_Init();
LcdInit();
while(1)
{
LED = !LED;
uidistance = Distance1();
LcdShowNum(2,3,uidistance);
delay_ms(20);
}
}
|