#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 Timer0_Init(void);
void Timer1_Init(void);
unsigned int Get_Distance(void);
void delayms();
void write_com();
void write_data();
void lcd1602init();
bit flag;
uint dValue;
unsigned int cnt;
static uchar flag1;
static uchar AUTO_flag;
uchar code lcdline1[]="Welcome To Use!" ;
uchar code lcdline2[]=" Table Lamp " ;
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 main(void)
{
uint i;
// cNum=0;
lcd1602init();
delayms(1000);
Timer0_Init();
Timer1_Init();
write_com(0x80);
for(i=0;i<15;i++)
{
write_data(lcdline1[i]);
delayms(100);
}
write_com(0x80+0x40);
for(i=0;i<14;i++)
{
write_data(lcdline2[i]);
delayms(100);
}
delayms(100);
while(1)
{
dValue=Get_Distance();
lcd1602init();
write_com(0x80);
write_data(0x30+dValue/100);
write_data(0x30+dValue%100/10);
write_data(0x30+dValue%10);
delayms(100);
}
}
/***********开启定时器1并初始化***************/
void Timer1_Init(void)
{
TMOD= 0x11;
TH1=TL1=0;
EA =1;
TR1=0;
}
void Timer1_ISR() interrupt 3
{
flag=1;
}
/***********开启定时器0并初始化***************/
void Timer0_Init(void)
{
TMOD =0x01;
TH0=(65536-100)/256;
TL0=(65536-100)%256;
EA =1;
TR0=1;
ET0=1;
}
void Timer0_ISR()interrupt 1
{
TR0=0;
TH0=(65536-100)/256;
TL0=(65536-100)%256;
cnt++;
if(cnt==20)
{
cnt=0;
}
TR0=1;
}
unsigned int Get_Distance(void)
{
unsigned int distance;
uint t=100;
TRIG=1;
while(t--);
TRIG=0;
while(!ECHO);
TR1=1;
while(ECHO);
TR1=0;
distance=TH1*256+TL1;
distance=distance*0.017;
TH1=0;
TL1=0;
delayms(20);
return distance;
}
|