利用51hei預留接口,用US-100超聲波模塊,1602顯示,精度還行。
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
#define lcd P0
sbit trig=P1^0;
sbit echo=P1^1;
sbit en=P3^4;
sbit rw=P2^7;
sbit rs=P3^5;
sbit busybit=P0^7;
sbit P24=P2^4;
sbit P26=P2^6;
sbit P27=P2^7;
bit test_flag;
uchar tab[]="0123456789";
void wr_com(uchar com,busyflag);
void delay(uint temp)
{
while(temp--);
//1620-14.99ms
//520-5ms
//5-450ns
}
void lcd_init(void)
{
delay(1650);//time
wr_com(0x38,0);
delay(550);//time
wr_com(0x38,0);
delay(550);
wr_com(0x38,0);
wr_com(0x38,1);
wr_com(0x08,1);
wr_com(0x01,1);
wr_com(0x06,1);
wr_com(0x0c,1);
}
void init(void)
{
P24=0;
P26=1;
P0=0x00;
P26=0;
P27=1;
P0=0xff;
P27=0;
TMOD=0x01;
TH0=0;
TL0=0;
TR0=0;//
IT0=1;
EX0=1;
EA=1;
lcd_init();
}
void testbusy(void)//read com
{
busybit=1;
en=0;
rs=0;
rw=1;
delay(5);
en=1;
delay(5);
while (busybit);
en=0;
}
void wr_dat(uchar dat,busyflag)
{
if(busyflag)
testbusy();
en=0;
rs=1;
rw=0;
lcd=dat;
delay(5);
en=1;
delay(5);
en=0;
}
void wr_com(uchar com,busyflag)
{
if(busyflag)
testbusy();
en=0;
rs=0;
rw=0;
lcd=com;
delay(5);
en=1;
delay(5);
en=0;
}
uint test_distance(void)
{
uint value;
TH0=0;
TL0=0;
trig=0;
_nop_();
trig=1;
_nop_();_nop_();_nop_();_nop_();_nop_();
_nop_();_nop_();_nop_();_nop_();_nop_();
trig=0;
while(!echo);
TR0=1;
while(echo);
TR0=0;
value=TH0*256+TL0;
return value;
}
void int0_srv() interrupt 0
{
test_flag=1;
}
void main()
{
uint value;
uint a,b,c,d;
init();
while(1)
{
if(test_flag)
{
test_flag=0;
EA=0;
value=test_distance();
a=value/100;
b=a/2;
c=b*340;
d=c/10;
a=d/1000;
b=(d%1000)/100;
c=((d%1000)%100)/10;
d=d%10;
EA=1;
}
wr_com(0x80,1);
delay(5);
wr_dat(tab[a],1);
delay(5);
wr_dat('.',1);
delay(5);
wr_dat(tab,1);
delay(5);
wr_dat(tab[c],1);
delay(5);
wr_dat(tab[d],1);
delay(5);
wr_dat('m',1);
delay(5);
}
}
|