#include<reg52.h> //距离超过150cm就报警
#define uchar unsigned char
#define uint unsigned int
sbit du=P2^6;
sbit we=P2^7;
sbit beep=P2^3;
sbit Trig=P1^0;
sbit Echo=P3^2;
int succeed_flag,time;
uchar timeH,timeL;
uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
void delay(uint x)
{
uint y;
for(;x>0;x--)
for(y=110;y>0;y--);
}
void delay_20us(uchar a)
for(a=0;a<100;a++);
void display(uint temp)
{
uchar bai,shi,ge;
bai=temp/100;
shi=temp%100/10;
ge=temp%10;
du=0;
P0=table[ge];
du=1;
du=0;
we=0;
P0=0x7b;
we=1;
we=0;
delay(5);
du=0;
P0=table[shi];
du=1;
du=0;
we=0;
P0=0x7d;
we=1;
we=0;
delay(5);
du=0;
P0=table[bai];
du=1;
du=0;
we=0;
P0=0x7e;
we=1;
we=0;
delay(5);
if(temp<50)
beep=0;
else
beep=1;
}
void main()
{
uint distance;
Trig=0;
EA=1;
TMOD=0x10;
while(1)
{
EA=0;
Trig=1;
delay_20us();
Trig=0;
while(Echo==0);
succeed_flag=0;
EA=1;
EX0=1;
TH1=0;
TL1=0;
TF1=0;
TR1=1;
delay(20);
TR1=0;
EX0=0;
if(succeed_flag==1)
{
time=timeH*256+timeL;
distance=time*0.0172;
}
if(succeed_flag==0)
{
distance=0;
}
display(distance);
}
}
void exter() interrupt 0
{
EX0=0;
timeH=TH1;
timeL=TL1;
succeed_flag=1;
}
/*void timer interrupt 3
{
TH1=0;
TL1=0;
}*/
|