#include<intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit trig=P3^3;
//发射
sbit echo=P3^2; //接收
sbit lcde=P2^7; //e
sbit wr=P2^5;
sbit rd=P2^6;
void delay(uint z);
void com(uchar com);
void writedata(uchar date);
void display(uchar temp);
uchar num,i;
uchar table1[3];
int
time,distance,succeedflag;
void lcdinit();
void main()
{
EA=1;
TMOD=0X01;
ET0=1;
while(1)
{
succeedflag=0;
trig=1;
delay(10);
trig=0;
while(!echo);
TR0=1;
TH0=0;
TL0=0;
while(echo);
TR0=0;
succeedflag=1;
delay(40);
}
if(succeedflag==1)
{
time=TH0*256+TL0;
distance=time*0.0172; //cm
display(distance);
}
if(succeedflag==0)
{
distance=0;
}
}
void delay(uint z) //延时函数
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void com(uchar com) //lcd命令
{
rd=0;
wr=0;
P0=com;
delay(5);
lcde=1;
delay(5);
lcde=0;
}
void writedata(uchar date) //lcd数据
{
rd=1;
wr=0;
P0=date;
delay(5);
lcde=1;
delay(5);
lcde=0;
}
void lcdinit() //lcd命令
{
com(0x38);
com(0x0c);
com(0x06);
com(0x01);
com(0x80);
}
void display(uchar temp) //记数
{
uchar bai,shi,ge,i,j;
bai=temp/100;
shi=temp%100/10;
ge=temp%10;
table1[0]=bai+'0';
table1[1]=shi+'0';
table1[2]=ge+'0';
lcdinit();
for(i=0;i<3;i++)
{
writedata(table1[i]);
}
}
void timer0() interrupt 1 //定时器0中断
{
TH0=0;
TH0=0;
}
一周热门 更多>