#include "reg52.h"
sbit Trig=P1^6;
sbit Echo=P1^7;
sbit D5=P3^7;
sbit D6=P3^6;
sbit sg90=P1^1;
sbit key1=P2^1;
sbit ZD=P3^2;
sbit Bee=P2^0;
int jd;
int cnt;
int mark=0;
int bark;
void Time0init()
{
TMOD&=0xF0;
TMOD|=0x01;
TL0=0x33;
TH0=0xFE;
TR0=1;
TF0=0;
ET0=1;
EA=1;
}
void Time1init()
{
TMOD &= 0x0F; //设置定时器模式
TMOD |= 0x10;
TH1=0;
TL1=0;
}
void Init_EX0()
{
EX0=1;
IT0=0;
}
void Delay10us()
{
unsigned char i;
i = 2;
while (--i);
}
void Delay50ms() //@11.0592MHz
{
unsigned char i, j;
i = 90;
j = 163;
do
{
while (--j);
} while (--i);
}
void Delay2000ms() //@11.0592MHz
{
unsigned char i, j, k;
i = 15;
j = 2;
k = 235;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void Start_HC() //发送超声波
{
Trig=0;
Trig=1;
Delay10us();
Trig=0;
}
double Get_distance()//获取距离信息
{
double dis;
double Time;
TH1=0;
TL1=0;
Start_HC();
while(Echo==0);
TR1=1;
while(Echo==1);
TR1=0;
Time=(TH1*256+TL1)*1.085;
dis=0.017*Time;
return dis;
}
void Initsg90_0()
{
jd=1;
cnt=0;
sg90=1;
}
void Open()
{
int i;
jd=3;
if(bark!=jd)
{
cnt=0;
Bee=0;
D5=0;
D6=1;
for( i=0;i<5;i++)
Delay50ms();
Bee=1;
Delay2000ms();
}
bark=jd;
}
void Close()
{
D5=1;
D6=0;
jd=1;
bark=jd;
cnt=0;
Delay50ms();
}
void main()
{
double Distance;
Time1init();
Time0init();
Init_EX0();
Initsg90_0();
while(1)//超声波测距
{
Distance=Get_distance();
if(Distance<10||key1==0||mark==1)
{
Open();
mark=0;
}
else
Close();
}
}
void Time0rupt() interrupt 1
{
cnt++;
TL0=0x33;
TH0=0xFE;
if(cnt<jd)
sg90=1;
else
sg90=0;
if(cnt==40)
{
cnt=0;
sg90=1;
}
}
void EX0rupt() interrupt 0
{
mark=1;
}
04-25
12-23
1455
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)