#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
unsigned int time;
unsigned int S;
sbit a1=P0^0;
sbit a2=P0^1;
sbit a3=P0^2;
sbit a4=P0^3;
sbit a5=P0^4;
sbit a6=P0^5;
sbit a7=P0^6;
sbit a8=P0^7;
sbit Trig =P1^3; //定义引脚
sbit Echo=P3^2;
void houM();
void leftM();
void stopM();
void Count();
void qianM();
void bz();
void zizhu();
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void exter0() interrupt 0 //中断
{
Count();EX0=0;
}
void T0_timer() interrupt 1 //中断
{
TH0=0;
TL0=0;
TR0=0;
}
void StartModule() //启动模块
{
Trig=1; //启动一次模块
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
Trig=0;
}
void uart(void) interrupt 4 //把接收到的数据写入ucReceiveData()
{
TI=0;RI=0;
if(SBUF=='a') a1=0;
if(SBUF=='b') a1=1;
if(SBUF=='c') a2=0;
if(SBUF=='d') a2=1;
if(SBUF=='e') a3=0;
if(SBUF=='f') a3=1;
if(SBUF=='g') a4=0;
if(SBUF=='h') a4=1;
if(SBUF=='i') a5=0;
if(SBUF=='j') a5=1;
if(SBUF=='k') a6=0;
if(SBUF=='l') a6=1;
if(SBUF=='m') a7=0;
if(SBUF=='n') a7=1;
if(SBUF=='o') a8=0;
if(SBUF=='p') a8=1;
if(SBUF=='r'){zizhu();}
}
void zizhu()
{
Trig=0;
Echo=0;
qianM();
while(1)
{
StartModule();
while(!Echo); //当echo为1时计数工作。中断没有
{TR0=1;EX0=0;} //开启计数
while(Echo); //当echo为0计数停止,进行bz核算
{
TR0=0; //关闭计数
EX0=1; //计算
delay(120);//80MS?
}
}
}
void Count(void)
{
time=TH0*256+TL0;
TH0=0;
TL0=0;
S=(time*1.7)/100; //算出来是CM
if((S<30)&&(S>10))
{
bz();
}
}
void init()
{
TMOD=0x21; //定时器1--方式2
PCON=0x00; //电源控制
SCON=0x50;
TL1=0xfd;
TH1=0xfd;
TR1=1;
TR0=1; //启动定时
TH0=0;
TL0=0;
ET0=1; //允许T0中断
ES=1;
EA=1;
TI=0;
RI=0;
}
void bz()
{
houM();
delay(10000);
leftM();
delay(10000);
stopM();
delay(1000);
qianM();
}
void houM()
{
a3=1;a8=1;
a1=0;a2=1;
a6=1;a7=0;
}
void leftM()
{
a3=1;a8=1;
a1=1;a2=0;
a6=1;a7=0;
}
void qianM()
{
a3=1;a8=1;
a1=1;a2=0;
a6=0;a7=1;
}
void stopM()
{
a3=0;a8=0;
a1=0;a2=0;
a6=0;a7=0;
}
void main()
{
init();while(1);
}
|