这个是我刚刚写的一个超声波测距的代码,麻烦大佬帮忙看看是哪出错了啊,调了一下午都没能正确显示距离,若有大佬帮忙解决,小的定当感激不尽
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
int time;
int succeed_flag;
uchar timeL;
uchar timeH;
sbit Trig =P1^0;
sbit Echo =P3^2;
sbit rs =P2^0;
sbit lcden=P2^2;
sbit rw =P2^1;
uchar table[]={
0x30,0x31,0x32,0x33,0x34,0x35,
0x36,0x37,0x38,0x39,0x3a};
uchar code *table1[]={"x zhou:","y zhou:"};
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void delay_20us()
{
uchar a ;
for(a=0;a<100;a++);
}
void lcdwrdata(uchar dat)
{
rs=1;
lcden=1;
P0=dat;
delay(6);
lcden=0;
delay(6);
}
void lcdwrcom(uchar cdat)
{
rs=0;
lcden=1;
P0=cdat;
delay(6);
lcden=0;
delay(6);
}
void lcd_init()
{
lcdwrcom(0x38);
lcdwrcom(0x0c);
lcdwrcom(0x06);
lcdwrcom(0x01);
}
void display(uint temp)
{
uchar ge,shi,bai;
bai=temp/100;
shi=(temp%100)/10;
ge=temp%10;
rw=0;
delay(200);
lcden=0;
lcd_init();
lcdwrcom(0x00|0x80);
while(*table1[0]!='\0')
{
lcdwrdata(*table1[0]++);
delay(100);
}
lcdwrcom(0x00|0xc0);
while(*table1[1]!='\0')
{
lcdwrdata(*table1[1]++);
delay(100);
}
lcdwrcom(0x08|0xc0);
lcdwrdata(table[ge]);
delay(1);
lcdwrcom(0x09|0xc0);
lcdwrdata(table[shi]);
delay(1);
lcdwrcom(0x0a|0xc0);
lcdwrdata(table[bai]);
delay(1);
}
void main()
{
uint distance;
Trig=0;
EA=1;
TMOD=0x10;
while(1)
{
EA=0;
Trig=1;
delay_20us();
Trig=0;
while(Echo==0);
succeed_flag=0;
EA=1;
EX0=1;
TH1=0;
TL1=0;
TF1=0;
TR1=1;
delay(20);
TR1=0;
EX0=0;
if(succeed_flag==1)
{
time=timeH*256+timeL;
distance=time*0.0172;
}
if(succeed_flag==0)
{
distance=0;
}
display(distance);
}
}
void exter() interrupt 0
{
EX0=0;
timeH =TH1;
timeL =TL1;
succeed_flag=1;
}
void timer1() interrupt 3
{
TH1=0;
TL1=0;
}
|