2 u012052289 u012052289 于 2014.03.07 00:14 提问

hc-sr04驱动 问题:烧入开发板之后,结果距离隔一段时间就突然增大。请大侠解答。

#include
#include
#include
sbit rs=P2^0;
sbit rw=P2^1;
sbit en=P2^2;
sbit TRIG = P3^3;
sbit ECHO = P3^2;
#define uchar unsigned char
#define ulong unsigned long
#define uint unsigned int
uchar table4[] = "Dis:";
uchar Dis0[4] = {0}; //存储距离
uchar sign[3] = 0;
uint Distance = 0;
unsigned long Time = 0;
void lcd_dischar (uchar ch);
void lcd_distring(uchar p);
void delay(uint n)
{
uint x,y;
for(x=n;x>0;x--)
for(y=110;y>0;y--);
}

void lcd_writecom(uchar com)
{
rs=0;
rw=0;
P0=com;
delay(5);
en=1;
en=0;
}
void lcd_writedat(uchar dat)
{
rs=1;
rw=0;
P0=dat;
delay(5);
en=1;
en=0;
}
void lcd_init(void)
{
lcd_writecom(0x38);
lcd_writecom(0x06);
lcd_writecom(0x0c);
lcd_writecom(0x01);
}
void lcd_distring(uchar *p)
{
uchar count,i;
uchar a[16];
strcpy(a,p);
count=strlen(a);
for(i=0;i {
lcd_writedat(a[i]);
}
}
/*void Measure(void)
{
unsigned long Time;
uint ge,shi,bai;
float D;
ECHO = TRIG = 0;
TMOD = 0X11;
TH1 = 0XFF;
TL1 = 0XF1;
TH0 = TL0 = 0;
IE = 0X8A;
TRIG = 1;
TR1 = 1;
while(!ECHO){}
TR1 = 0;
TR0 = 1;
while(ECHO){}
TR0 = 0;
Time = TH0*256+TL0;
TH0 = TL0 = 0;
Distance = ((unsigned long)Time*344)/2000;
D = Distance/10.0;
if(Distance>0&&Distance<900)
{
bai = Distance/100;
shi = Distance/10-(bai*10);
ge = Distance-bai*100-shi*10;
Dis0[0] = bai+'0';
Dis0[1] = shi+'0';
Dis0[2] = '.';
Dis0[3] = ge+'0';
}
else
Dis0[0] = Dis0[1] = Dis0[2] = Dis0[3] = 0x20;

}
/
void lcd_dischar(uchar ch)
{
lcd_writedat(ch);
}
void main(void)
{
uchar i;
uint ge,shi,bai,qian;
lcd_init();
TMOD = 0X19;
EA = 1;
TR0 = 1;
EX0 = 1;
IT0 = 1;
while(1)
{
// Measure();
TRIG = 1;
nop(); nop();
nop(); nop();
nop(); nop();
nop(); nop();
nop(); nop();
nop(); nop();
nop(); nop();
nop(); nop();
TRIG = 0;
Distance = 0.17*Time;
qian = Distance/1000;
bai = Distance/100-qian*10;
shi = Distance/10-qian*100-bai*10;
ge = Distance%10;
Dis0[0] = qian+'0';
Dis0[1] = bai+'0';
Dis0[2] = shi+'0';
Dis0[3] = ge+'0';
for(i=0;i<10;i++)
{
lcd_writecom(0x80+0x00);
lcd_distring(table4);
lcd_dischar(Dis0[0]);
lcd_dischar(Dis0[1]);
lcd_dischar(Dis0[2]);
lcd_dischar(Dis0[3]);
}

}

}
void int0() interrupt 0
{
Time=TH0*256+TL0;
TH0 = 0;
TL0 = 0;
}

Csdn user default icon
上传中...
上传图片
插入图片