#include "reg52.h"
#include "Delay.h"
#define uchar unsigned char
#define uint unsigned int
sbit BEEP=P2^6; //蜂鸣器
sbit RUN=P2^5; //直流电机
sbit Trig=P1^5; //555使能端
sbit Echo=P1^6; //接收端
uchar outcomeH,outcomeL;
uint i,distance,y;
enum state_all{n1,n2,n3,n4,n5}state;
void startset(void) //初始化
{ TMOD=0x01; //方式1
TH0=0x00;
TL0=0x00;
BEEP=0; //关蜂鸣器
RUN=1; //开电机
ET0=1; //开定时器0
EA=1; //开启外部总中断
y=0;
}
void Init_Parameter(void) //清零
{
TH0=0x00;
TL0=0x00;
}
void Trig_voice(void) //出发声波
{
Trig=1;
TR0=1; //启动定时器0
}
void Change_Distance(void) //计算距离
{ if(Echo==1)
{
EX0=1;
}
}
void BJ_Distance(void) //比较距离
{ if(y<15.0)
{
RUN=0;
BEEP=1;
}
else
{ RUN=1;
BEEP=0;
}
}
void main()
{ Delayms(10);
startset();
state=n1;
while(1)
{
switch (state)
{ case n1: Init_Parameter(); //清零
state=n2;
break;
case n2: Trig_voice(); // 发送声波
state=n3;
break;
case n3: Change_Distance(); //计算距离
state=n4;
break;
case n4: BJ_Distance(); //比较距离
Delayms(50);
state=n1;
break;
}
}
}
timer0() interrupt 1 // 定时器0中断是1号
{
TH0=0x00;
TL0=0x00;
state=n1;
}
INTO_() interrupt 0 //外部中断是0号
{ TR0=0;
outcomeL=TL0;//取出定时器的值
outcomeH=TH0;
i=(outcomeH*256)+outcomeL;
distance=(int)((i*0.034)/2.0);
y=distance;
EX0=0; //关闭外部中断
state=n4;
} |