#include
#define uint unsigned int
#define uchar unsigned char
uchar code table[]="0123456789.m";
uchar code table1[]="too far";
uchar code table2[]="the distance is:";
uchar code table3[]="please wait";
sbit lcden=P2^0;
sbit lcdrs=P2^1;
sbit trig=P2^2;
sbit echo=P3^2;
uint succeed;
float t,d,timeh,timel;
uint distance;
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void delay20us()
{
_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();
_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();_nop_();
}
void display( )
{
uchar i;
init(); //1602初始化
write_com(0x80);
for(i=0;i<16;i++)
{
write_data(table2[i]);
delay(5);
}
write_com(0x80+0x45);
i=distance/10000;
write_data(table[i]);delay(5);
i=distance%10000/1000; //千位
write_data(table[i]);delay(5);
i=distance%1000/100; //百位
write_data(table[i]);delay(5);
i=(distance%100)/10;
write_data(table[i]);delay(5);
i=distance%10;
write_data(table[i]);delay(5);
write_data(table[11]);delay(5);
write_data(table[11]);delay(5);
}
void main()
{
trig=0;
echo=0;
EA=1;
IT0=1;
TMOD=0x01;
while(1)
{
trig=0; ////////
echo=0; //////
EA=0;
trig=1;
delay20us();
trig=0;
while(echo==0);
succeed=0;
EA=1;
EX0=1;
TH1=0;
TL1=0;
TF1=0;
TR1=1;
delay(60);
if(succeed==1)
{
t=(timeh*256+timel)*1.09;
d=t*0.17;
distance=(int)d;
display();
}
if(succeed==0)
{
distance=0;
displaywait();
}
delay(500);
}
}
void ex0()interrupt 0
{
timeh=TH1;
timel=TL1;
succeed=1;P1=~P1;
EX0=0;
}
void et1()interrupt 3
{
TH1=0;
TL1=0;
displaytoofar();
EA=0;
}
由于字数限制我把1602的初始化部分和自己加的小部分删掉了