52单片机超声波测距并用lcd1602显示
时间: 2023-07-03 15:10:09 浏览: 88
这个项目需要使用52单片机和超声波传感器来测量距离,并将结果显示在LCD1602上。以下是详细步骤:
1. 连接硬件:将超声波传感器的Trig引脚连接到P1.0口,Echo引脚连接到P1.1口,LCD1602的RS、RW、E分别连接到P2.0、P2.1、P2.2口,D4-D7四个引脚分别连接到P2.4-P2.7口。
2. 初始化LCD1602:在主函数中调用LCD1602_Init()函数,初始化LCD1602。
3. 初始化定时器:使用定时器来控制超声波的发射和接收时间,需要在主函数中调用Timer0_Init()函数,初始化定时器。
4. 测距并显示结果:在主函数中调用MeasureDistance()函数,测量距离并将结果显示在LCD1602上。
下面是代码示例:
```c
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit TRIG = P1^0;
sbit ECHO = P1^1;
sbit RS = P2^0;
sbit RW = P2^1;
sbit E = P2^2;
sbit LCD_D4 = P2^4;
sbit LCD_D5 = P2^5;
sbit LCD_D6 = P2^6;
sbit LCD_D7 = P2^7;
void delay_us(uint us)
{
while(us--)
_nop_();
}
void delay_ms(uint ms)
{
uchar i, j;
while(ms--)
for(i=0; i<250; i++)
for(j=0; j<255; j++);
}
void LCD1602_WriteCmd(uchar cmd)
{
RS = 0;
RW = 0;
LCD_D7 = cmd >> 7;
LCD_D6 = (cmd >> 6) & 0x01;
LCD_D5 = (cmd >> 5) & 0x01;
LCD_D4 = (cmd >> 4) & 0x01;
E = 1;
_nop_();
E = 0;
LCD_D7 = (cmd >> 3) & 0x01;
LCD_D6 = (cmd >> 2) & 0x01;
LCD_D5 = (cmd >> 1) & 0x01;
LCD_D4 = cmd & 0x01;
E = 1;
_nop_();
E = 0;
delay_us(50);
}
void LCD1602_WriteData(uchar dat)
{
RS = 1;
RW = 0;
LCD_D7 = dat >> 7;
LCD_D6 = (dat >> 6) & 0x01;
LCD_D5 = (dat >> 5) & 0x01;
LCD_D4 = (dat >> 4) & 0x01;
E = 1;
_nop_();
E = 0;
LCD_D7 = (dat >> 3) & 0x01;
LCD_D6 = (dat >> 2) & 0x01;
LCD_D5 = (dat >> 1) & 0x01;
LCD_D4 = dat & 0x01;
E = 1;
_nop_();
E = 0;
delay_us(50);
}
void LCD1602_Init()
{
delay_ms(15);
LCD1602_WriteCmd(0x38);
delay_ms(5);
LCD1602_WriteCmd(0x38);
delay_ms(5);
LCD1602_WriteCmd(0x38);
delay_ms(5);
LCD1602_WriteCmd(0x08);
delay_ms(5);
LCD1602_WriteCmd(0x01);
delay_ms(5);
LCD1602_WriteCmd(0x06);
delay_ms(5);
LCD1602_WriteCmd(0x0c);
delay_ms(5);
}
void Timer0_Init()
{
TMOD |= 0x01;
TH0 = 0;
TL0 = 0;
ET0 = 1;
TR0 = 1;
}
void MeasureDistance()
{
uchar distance;
uint time;
TRIG = 0;
delay_us(2);
TRIG = 1;
delay_us(10);
TRIG = 0;
while(!ECHO);
TH0 = 0;
TL0 = 0;
while(ECHO);
time = TH0 * 256 + TL0;
distance = time / 58;
LCD1602_WriteCmd(0x80);
LCD1602_WriteData('D');
LCD1602_WriteData('i');
LCD1602_WriteData('s');
LCD1602_WriteData('t');
LCD1602_WriteData('a');
LCD1602_WriteData('n');
LCD1602_WriteData('c');
LCD1602_WriteData('e');
LCD1602_WriteCmd(0x8f);
LCD1602_WriteData(distance / 100 + '0');
LCD1602_WriteData(distance % 100 / 10 + '0');
LCD1602_WriteData(distance % 10 + '0');
LCD1602_WriteData('c');
LCD1602_WriteData('m');
}
void main()
{
LCD1602_Init();
Timer0_Init();
while(1)
{
MeasureDistance();
delay_ms(500);
}
}
void Timer0_ISR() interrupt 1
{
TH0 = 0;
TL0 = 0;
}
```
其中,delay_us()和delay_ms()函数用来延时,LCD1602_WriteCmd()和LCD1602_WriteData()函数用来向LCD1602写入指令和数据,LCD1602_Init()函数用来初始化LCD1602,Timer0_Init()函数用来初始化定时器,MeasureDistance()函数用来测量距离并显示结果。在主函数中,先调用LCD1602_Init()和Timer0_Init()函数进行初始化,然后进入循环,不停地调用MeasureDistance()函数测量距离并显示结果,每次测量完毕后延时500ms,以免频繁测量导致干扰。最后,定时器中断服务程序Timer0_ISR()用来清零定时器计数器。
阅读全文