52单片机超声波测距用lcd1602显示程序
时间: 2023-07-26 11:03:25 浏览: 144
下面是基于STC89C52单片机和超声波模块HC-SR04的测距程序,使用LCD1602显示距离值。
```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 = P1^0;
sbit Echo = P1^1;
void delay_us(uint us)
{
while (us--)
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
}
void delay_ms(uint ms)
{
while (ms--)
{
delay_us(1000);
}
}
void lcd_write_com(uchar com)
{
RS = 0;
RW = 0;
P0 = com;
EN = 1;
delay_us(5);
EN = 0;
}
void lcd_write_data(uchar dat)
{
RS = 1;
RW = 0;
P0 = dat;
EN = 1;
delay_us(5);
EN = 0;
}
void lcd_init()
{
lcd_write_com(0x38);
delay_ms(5);
lcd_write_com(0x38);
delay_ms(5);
lcd_write_com(0x38);
delay_ms(5);
lcd_write_com(0x0C);
delay_ms(5);
lcd_write_com(0x06);
delay_ms(5);
lcd_write_com(0x01);
delay_ms(5);
}
void lcd_clear()
{
lcd_write_com(0x01);
delay_ms(5);
}
void lcd_set_cursor(uchar x, uchar y)
{
uchar addr;
if (y == 0)
{
addr = 0x80 + x;
}
else
{
addr = 0xC0 + x;
}
lcd_write_com(addr);
delay_ms(5);
}
void lcd_display_string(uchar x, uchar y, uchar *str)
{
lcd_set_cursor(x, y);
while (*str)
{
lcd_write_data(*str++);
}
}
uint ultrasonic_measure()
{
uint distance;
Trig = 0;
delay_us(2);
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()
{
uchar str[16];
TMOD = 0x01;
TH0 = 0;
TL0 = 0;
lcd_init();
lcd_display_string(0, 0, "Distance: ");
while (1)
{
uint distance = ultrasonic_measure();
sprintf(str, "%d cm ", distance);
lcd_display_string(10, 0, str);
delay_ms(500);
}
}
```
注意:在程序中需要使用定时器 T0 来计时,因此需要将 P3.4(T0)设置为输出,并且在程序中使用 T0 计时时需要开启定时器 T0。代码中使用的是 12MHz 的外部晶振,如果使用其他频率的晶振需要相应调整计时参数。
阅读全文