你可以尝试以下的代码:
```
#include <reg52.h>
#include <intrins.h>
#define LCDDataPort P2
sbit RS=P0^0;
sbit RW=P0^1;
sbit EN=P0^2;
void delay_ms(unsigned int ms)
{
unsigned int i, j;
for (i = 0; i < ms; i ++)
{
for (j = 0; j < 90; j ++);
}
}
void delay_us(unsigned int us)
{
while(us--)
_nop_();
}
void WriteCommand(unsigned char Command)
{
RS = 0;
EN = 1;
RW = 0;
LCDDataPort = Command;
delay_us(5);
EN = 0;
delay_ms(1);
}
void WriteData(unsigned char Data)
{
RS = 1;
EN = 1;
RW = 0;
LCDDataPort = Data;
delay_us(5);
EN = 0;
delay_ms(1);
}
void delay(int x)
{
int i,j;
for(i=0;i<x;i++)
for(j=0;j<125;j++);
}
void InitLcd1602()
{
WriteCommand(0x38);
WriteCommand(0x0c);
WriteCommand(0x06);
WriteCommand(0x01);
delay_ms(10);
}
void Display(unsigned char X,unsigned char Y,unsigned char DispData[])
{
unsigned char i;
if(X<16)
{
X = 0x80 + X;
WriteCommand(X);
}
else
{
X = 0x80 + 0x40 + X-16;
WriteCommand(X);
}
for(i=0;i<Y;i++)
{
WriteData(DispData[i]);
}
}
void WriteChar(unsigned char X,unsigned char Y,unsigned char DData)
{
if(X<16)
{
X = 0x80 + X;
WriteCommand(X);
}
else
{
X = 0x80 + 0x40 + X-16;
WriteCommand(X);
}
WriteData(DData);
}
void main()
{
unsigned char buf[16];
unsigned char temp;
unsigned int dis;
InitLcd1602();
while(1)
{
WriteCommand(0x01);
WriteChar(0,0,'H');
WriteChar(1,0,'C');
WriteChar(2,0,'-');
WriteChar(3,0,'S');
WriteChar(4,0,'R');
WriteChar(5,0,'0');
WriteChar(6,0,'4');
WriteChar(9,0,'D');
WriteChar(10,0,'I');
WriteChar(11,0,'S');
WriteChar(12,0,'T');
WriteChar(13,0,'A');
WriteChar(14,0,'N');
WriteChar(15,0,'C');
delay(20);
WriteCommand(0x01);
WriteChar(0,0,'D');
WriteChar(1,0,'I');
WriteChar(2,0,'S');
WriteChar(3,0,'T');
WriteChar(4,0,'A');
WriteChar(5,0,'N');
WriteChar(6,0,'C');
WriteChar(9,0,'M');
WriteChar(10,0,'E');
WriteChar(11,0,'T');
WriteChar(12,0,'E');
WriteChar(13,0,'R');
WriteChar(14,0,':');
WriteChar(15,0,' ');
WriteCommand(0x80+0x40+2);
WriteChar(2,1,'C');
WriteChar(3,1,'M');
WriteChar(4,1,':');
WriteChar(5,1,' ');
WriteCommand(0x80+0x40+9);
WriteChar(9,1,'I');
WriteChar(10,1,'N');
WriteChar(11,1,'C');
WriteChar(12,1,'H');
WriteChar(13,1,' ');
WriteChar(14,1,'E');
WriteChar(15,1,'S');
temp=P1;
P3_6=1;
delay(100);
P3_6=0;
while(!P1);
TR0=1;
while(P1);
TR0=0;
dis=TH0;
dis<<=8;
dis|=TL0;
dis/=58;
sprintf(buf,"%d ",dis);
Display(7,1,buf);
delay(200);
}
}
```
以上是使用Keil编写STC芯片LCD1602显示HC-SR04超声波测距代码。希望对您有所帮助!