51单片机超声波测距用lcd1602显示距离写个程序
时间: 2023-08-30 17:04:04 浏览: 95
以下是51单片机超声波测距用lcd1602显示距离的程序,供参考:
```c
#include<reg52.h>
#include<intrins.h>
#define LCD_dat P0
sbit LCD_RS = P2^0;
sbit LCD_RW = P2^1;
sbit LCD_EN = P2^2;
sbit Trig = P3^4;
sbit Echo = P3^5;
void delay_us(unsigned char us)
{
while(us--)
{
_nop_();
_nop_();
_nop_();
_nop_();
}
}
void delay_ms(unsigned char ms)
{
while(ms--)
{
delay_us(245);
delay_us(245);
delay_us(245);
delay_us(245);
}
}
void LcdWriteCmd(unsigned char cmd)
{
LCD_RS = 0;
LCD_RW = 0;
LCD_dat = cmd;
LCD_EN = 1;
delay_us(5);
LCD_EN = 0;
delay_us(5);
}
void LcdWriteDat(unsigned char dat)
{
LCD_RS = 1;
LCD_RW = 0;
LCD_dat = dat;
LCD_EN = 1;
delay_us(5);
LCD_EN = 0;
delay_us(5);
}
void LcdInit()
{
LcdWriteCmd(0x38);
LcdWriteCmd(0x0c);
LcdWriteCmd(0x06);
LcdWriteCmd(0x01);
}
void LcdClear()
{
LcdWriteCmd(0x01);
}
void LcdSetCursor(unsigned char x, unsigned char y)
{
if(y == 0)
LcdWriteCmd(0x80 + x);
else
LcdWriteCmd(0x80 + 0x40 + x);
}
void LcdPrintStr(char *str)
{
while(*str)
{
LcdWriteDat(*str++);
}
}
unsigned int Ultrasonic()
{
unsigned char i;
unsigned int distance;
Trig = 1;
delay_us(10);
Trig = 0;
while(!Echo);
TR0 = 1;
while(Echo);
TR0 = 0;
distance = TH0 * 256 + TL0;
distance = distance / 58;
return distance;
}
void main()
{
unsigned int distance;
TMOD = 0x09;
TH0 = 0;
TL0 = 0;
LcdInit();
LcdClear();
while(1)
{
distance = Ultrasonic();
LcdSetCursor(0, 0);
LcdPrintStr("Distance: ");
LcdSetCursor(0, 1);
LcdPrintStr(" ");
LcdSetCursor(0, 1);
LcdPrintStr(distance / 100 + '0');
LcdPrintStr(distance % 100 / 10 + '0');
LcdPrintStr(distance % 10 + '0');
delay_ms(500);
}
}
```
程序中使用了LCD1602库函数,并且通过超声波模块测量距离,并将结果显示在LCD1602上。在使用时,需要将Trig和Echo分别接到51单片机的P3.4和P3.5上,LCD1602的数据线接到P0口上,控制线分别接到P2.0、P2.1、P2.2上即可。
阅读全文