,结果只显示上电的那个距离,然后移动模块,距离不自动更新!求赐教!程序如下:
#include <STC12C5A60S2.h>
#include <intrins.h>
#define LCD1602_DB P0
//sfr AUXE=0x8E;//1T
sbit Trig=P3^2;
sbit Echo=P3^3;
sbit LCD1602_RS = P1^0;
sbit LCD1602_RW = P1^1;
sbit LCD1602_E = P1^5;
unsigned char code str1[]={"Ready..."};
unsigned char code str2[]={"Beyond range!"};
unsigned char code str3[]={"Measuring:"};
//unsigned char code ASCII[15] = {'0','1','2','3','4','5','6','7','8','9'};
unsigned char str5[6]={"CM"};
unsigned int time;
unsigned long distance;
bit flag=0;
/*等待液晶准备好*/
void lcdwaitready()
{
unsigned char sta;
LCD1602_DB=0xFF;//单片机读,先写入1
LCD1602_RS=0;
LCD1602_RW=1;
do
{
LCD1602_E=1;
sta=LCD1602_DB;
LCD1602_E=0;
}while(sta&0x80);
}
/*向LCD液晶写命令*/
void lcdwritecmd(unsigned char cmd)
{
lcdwaitready();
LCD1602_RS=0;
LCD1602_RW=0;
LCD1602_DB=cmd;
LCD1602_E=1;
LCD1602_E=0;
}
/*向LCD液晶写数据*/
void lcdwritedat(unsigned char dat)
{
lcdwaitready();
LCD1602_RS=1;
LCD1602_RW=0;
LCD1602_DB=dat;
LCD1602_E=1;
LCD1602_E=0;
}
/*设置起始坐标*/
void lcdsetcursor(unsigned char x,unsigned char y) //形参是局部变量,可以与其他冲突
{
unsigned char addr;
if(y==0)
addr=0x00+x;
else
addr=0x40+x;
lcdwritecmd(addr|0x80); //设置数据地址指针 0x80+addr
}
/*void lcdshowchar(unsigned char x,unsigned char y,unsigned char dat) //形参是局部变量,可以与其他冲突
{
unsigned char addr;
if(y==0)
addr=0x00+x;
else
addr=0x40+x;
lcdwritecmd(addr|0x80); //设置数据地址指针 0x80+addr
lcdwritedat(dat);
}*/
/*在液晶上显示字符串*/
void lcdshowstr(unsigned char x,unsigned char y,unsigned char *str)
{
lcdsetcursor(x,y);
while(*str!='\0')
{
lcdwritedat(*str++);
}
}
/*LCD初始化*/
void lcdinit()
{
lcdwritecmd(0x38); //16*2显示,5*7点阵,8位数据接口
lcdwritecmd(0x0C); //显示器开,光标关闭
lcdwritecmd(0x06); //文字不动,地址自动+1
lcdwritecmd(0x01); //清屏
}
void DELAY_MS (unsigned int a){
unsigned int i;
while( a-- != 0){
for(i = 0; i < 600; i++);
}
}
void Count()
{
unsigned char str4[10];
time=TH0*256+TL0;
TH0=0;
TL0=0;
distance=(time*1.72)/100;//单位为CM
if(distance>700||flag==1)
{
flag=0;
lcdshowstr(0,0,str2);
}
else
{
str4[0]=distance/100%10+'0';
str4[1]=distance/10%10+'0';
str4[2]=distance%10+'0';
lcdshowstr(0,0,str3);
lcdshowstr(0,1,str4);
lcdshowstr(3,1,str5);
}
}
void interrupttimer0() interrupt 1
{
flag=1;
}
void starmodul()
{
Trig=1; //启动一次模块
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
Trig=0;
}
void main()
{
lcdinit();
DELAY_MS(1000);
lcdshowstr(0,0,str1);
DELAY_MS(2000);
Trig=0;//首先拉低输入脉冲引脚
TMOD&=0xF0;
TMOD|=0x01;
TH0=0;
TL0=0;
ET0=1;
EA=1;
while(1)
{
starmodul();
while(!Echo);
TR0=1;
while(Echo);
TR0=0;
Count();
Echo=1;
}
}
|