#include <reg52.h>
sbit lcdrs=P3^5;
sbit lcdrw=P3^6;
sbit lcden=P3^4;
sbit TRIG = P1^0;
sbit ECHO =P1^1;
#define uint unsigned int
#define uchar unsigned char
void Timer1_Init();
unsigned int Get_Distance();
void delayms();
void write_com();
void write_data();
void lcd1602init();
bit flag;
uint dValue,tmp;
uchar code lcdline1[]="Welcome To Use!" ;
uchar code lcdline2[]="Table Lam is" ;
void delayms(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void write_com(uchar com)
{
lcdrs=0;
lcdrw=0;
lcden=0;
P0=com;
delayms(5);
lcden=1;
delayms(5);
lcden=0;
}
void write_data(uchar dat)
{
lcdrs=1;
lcdrw=0;
P0=dat;
delayms(5);
lcden=1;
delayms(5);
lcden=0;
}
void lcd1602init()
{
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
}
void writeString(uchar * str, uchar length)
{
uchar i;
for(i = 0; i < length; i++)
{
write_data(str[i]);
}
}
void display()
{
unsigned char count;
unsigned char datas[] = {0, 0, 0};
unsigned int tmp = Get_Distance();
datas[0] = tmp/100 ;
datas[1] = tmp%100/10;
datas[2] = tmp%10;
write_com(0x80+0x40+12);
for(count = 0; count < 3; count++)
{
write_data('0'+datas[count]); //写入能识别的字符 ’0‘+数值
}
}
void main(void)
{
lcd1602init();
Timer1_Init();
write_com(0x80);
writeString(lcdline1,15);
delayms(1000);
write_com(0x80+0x40);
writeString(lcdline2,12);
delayms(1000);
while(1)
{
display();
delayms(100);
}
}
/***********开启定时器1并初始化***************/
void Timer1_Init(void)
{
TMOD= 0x10;
TH1=0;
TL1=0;
EA =1;
TR1=0;
}
void Timer1_ISR() interrupt 3
{
flag=1;
}
unsigned int Get_Distance()
{
unsigned int distance;
uint t=100;
TRIG=1;
while(t--);
TRIG=0;
while(!ECHO);
flag=0;
TR1=1;
while(ECHO);
TR1=0;
distance=TH1*256+TL1;
distance=distance*0.017;
TH1=0;
TL1=0;
delayms(100);
return distance;
}
|