|
#include"reg51.h"
#include"intrins.h"
sbit lcdrs=P3^5;
sbit lcdrw=P3^6;
sbit lcden=P3^7;
sbit Trig=P2^6;
sbit Echo=P2^7;
bit flag=0;
unsigned char num[ ]="0123456789";
unsigned char dis1[ ]="The Distance is:";
unsigned char dis2[ ]="Error!";
unsigned int diistance;
//ÑÓʱº¯Êý
void delay(unsigned int z)
{
unsigned int x,y;
for(x=z;x>0;x--)
for(y=400;y>0;y--);
}
//LCDдָÁÊý
void lcdWriteCmd(unsigned char cmd)
{
lcdrs=0;
P1=cmd;
delay(1);
lcden=1;
delay(1);
lcden=0;
}
//дÊý¾Ýº¯Êý
void lcdWriteDate(unsigned char dat)
{
lcdrs=1;
P1=dat;
delay(20);
lcden=1;
delay(20);
lcden=0;
}
//LCDÇåÆÁº¯Êý
void clear()
{
lcdWriteCmd(0x01);
delay(5);
}
//LCD³õʼ»¯º¯Êý
void lcdInit()
{
lcden=0;
lcdWriteCmd(0x38);
lcdWriteCmd(0x0f);
lcdWriteCmd(0x06);
clear();
lcdWriteCmd(0x80);
}
//LCDÏÔʾ¾àÀ뺯Êý
void lcdDisplay(unsigned int temp)
{
unsigned int i;
for(i=0;i<17;i++)
{
lcdWriteCmd(dis1[i]);
}
lcdWriteCmd(0x80+0x40);
lcdWriteCmd(num[temp/100]);
lcdWriteCmd(num[temp/10%10]);
lcdWriteCmd(num[temp%10]);
lcdWriteCmd('c');
lcdWriteCmd('m');
delay(400);
clear();
}
//³¬Éù²¨²â¾àÆô¶¯º¯Êý
void start()
{
int i;
Trig=1;
for(i=0;i<20;i++)
{
_nop_();
}
Trig=0;
}
//¾àÀë¼ÆËãÓëÏÔʾº¯Êý
void lcdWriteData();
void count()
{
unsigned int i,distance,falseValue,time,timeH,timeL;
timeH=TH0;
timeL=TL0;
TH0=0;
TL0=0;
time=time*256+timeL;
distance=time*1.7/100;
if(distance<10||distance>200||flag==0)
{
flag=1;
falseValue=888;
lcdWriteCmd(0x80);
for(i=0;i<7;i++)
{
lcdWriteData(dis2[i]);
}
delay(200);
clear();
lcdDisplay(falseValue);
}
else
{
lcdDisplay(distance);
}
}
//Ö÷º¯Êý
void main()
{
lcdrw=0;
while(1)
{
lcdInit();
TMOD=0x11;
TH0=0;
TL0=0;
Trig=0;
Echo=0;
start();
while(!Echo);
TR0=1;
while(Echo);
TR0=0;
count();
delay(200);
}
}
|
|