#include "reg52.h"
sbit Trig=P1^5;
sbit Echo=P1^6;
sbit D5=P3^7;
sbit D6=P3^6;
sbit DIDI=P1^0;
void Delay10us() //@11.0592MHz
{
unsigned char i;
i = 2;
while (--i);
}
void Time0Init()
{
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x01; //设置定时器模式
TL0=0;
TH0=0;//不着急计时
}
void Delay100ms() //@11.0592MHz
{
unsigned char i, j;
i = 180;
j = 73;
do
{
while (--j);
} while (--i);
}
void StartHC()
{
Trig=0;
Trig=1;
Delay10us(); //发送一个10us的高电平的波激发超声波
Trig=0;
}
void main()
{
double time,dis;
//定义时间与距离
Time0Init();
//初始化定时器
while(1)
{
StartHC();
//激发超声波
while(Echo==0);
TR0=1;
//当Echo为高电平(超声波发出),开始计时
while(Echo==1);
TR0=0;
//当Echo为低电平(超声波返回),停止计时
time=(TH0*256+TL0)*1.085;
dis=time*0.017;
if(dis<15)
{
D5=0;
D6=1;
DIDI=0;
Delay100ms();
DIDI=1;
Delay100ms();
}
else
{
D5=1;
D6=0;
}
TH0=0;
TL0=0;
//计时器清零
}
}