51单片机超声波测距1602液晶显示程序代码
时间: 2023-12-06 13:38:06 浏览: 122
以下是基于51单片机的超声波测距1602液晶显示程序代码,使用Keil软件编写:
```c
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit RS = P2^6;
sbit RW = P2^5;
sbit EN = P2^7;
sbit Trig = P3^5;
sbit Echo = P3^2;
void delay(uint i)
{
while(i--);
}
void WriteCommand(uchar com)
{
RS = 0;
RW = 0;
P0 = com;
EN = 1;
_nop_();
_nop_();
EN = 0;
}
void WriteData(uchar dat)
{
RS = 1;
RW = 0;
P0 = dat;
EN = 1;
_nop_();
_nop_();
EN = 0;
}
void InitLCD()
{
WriteCommand(0x38);
WriteCommand(0x0c);
WriteCommand(0x06);
WriteCommand(0x01);
}
void Display(uchar *s)
{
while(*s)
{
WriteData(*s++);
}
}
void UltrasonicInit()
{
TMOD = 0x01;
TH0 = 0;
TL0 = 0;
Trig = 0;
Echo = 0;
}
uint UltrasonicMeasure()
{
uint distance;
Trig = 1;
delay(10);
Trig = 0;
while(!Echo);
TR0 = 1;
while(Echo);
TR0 = 0;
distance = TH0 * 256 + TL0;
distance = distance / 58;
return distance;
}
void main()
{
uchar str[16];
uint distance;
InitLCD();
UltrasonicInit();
while(1)
{
distance = UltrasonicMeasure();
sprintf(str, "Distance:%dcm", distance);
WriteCommand(0x80);
Display(str);
delay(1000);
}
}
```
阅读全文