/*******超声波测距程序*******/
#include
#include
#define uchar unsigned char
#define uint unsigned int
sbit rs = P2^4;
sbit rw = P2^5;
sbit en = P2^6;
sbit tr = P3^2;
sbit ec = P1^0;
uint distance = 0;
uchar count;
void delayms(uint x)
{
uint i,j;
for(i=x;i>0;i--)
for(j=110;j>0;j--);
}
void write_com(uchar com)
{
rs = 0;
rw = 0;
en = 0;
P0 = com;
delayms(2);
en = 1;
delayms(5);
en = 0;
delayms(2);
}
void write_dat(uchar dat)
{
rs = 1;
rw = 0;
en = 0;
P0 = dat;
delayms(2);
en = 1;
delayms(5);
en = 0;
delayms(2);
}
void Init_1602()
{
write_com(0x38);
delayms(5);
write_com(0x0c);
delayms(5);
write_com(0x06);
delayms(5);
write_com(0x01);
delayms(5);
}
void Init_TIMER0()
{
TMOD = 0x01;
TL0 = 0x66;
TH0 = 0xfc;
ET0 = 1;
EA = 1;
}
void Init_mk()
{
tr =1;
ec = 1;
count = 0;
distance = 0;
}
void init_fs()
{
ec= 1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
ec = 0;
}
void jsdistance()
{
uint y;
TR0 = 1;
while(tr);
TR0 = 0;
y = TH0*256+TL0;
y = y - 0xfc66;
distance = y + 1000 * count;
TL0 = 0x66;
TH0 = 0xfc;
delayms(30);
distance = 0.340 * distance / 2;
}
void display()
{
uchar qian,bai,shi,ge;
qian= (distance / 1000);
bai= (distance / 100) % 10;
shi = (distance / 10) % 10;
ge = distance % 10;
write_com(0x80+0x40+4);
write_dat(0x30+qian);
write_dat(0x30+bai);
write_dat(0x30+shi);
write_dat('.');
write_dat(0x30+ge);
write_dat('C');
write_dat('M');
}
void write_hz(uchar *p)
{
while(*p != 0)
write_dat(*p++);
delayms(500);
}
void main()
{
rw = 0;
Init_1602();
Init_TIMER0();
Init_mk();
while(1)
{
init_fs();
while(tr == 0)
{
;
}
jsdistance();
display();
Init_mk();
delayms(10);
write_com(0x80);
write_hz("****distance****");
}
}
void TIMER0() interrupt 1
{
TF0 = 0;
TL0 = 0x66;
TH0 = 0xfc;
count++;
if(count == 18)
{
TR0 =0;
TL0 = 0x66;
TH0 = 0xfc;
count = 0;
}
}