51单片机超声波测距l用cd1602显示程序
时间: 2023-08-31 14:06:22 浏览: 67
以下是51单片机超声波测距并用CD1602液晶显示的程序:
```c
#include <reg51.h>
#include <intrins.h>
#define LCD12864 P2
sbit RS = P1^0;
sbit RW = P1^1;
sbit E = P1^2;
sbit TRIG = P3^2;
sbit ECHO = P3^3;
unsigned int distance = 0;
void delay_us(unsigned int n)
{
while(n--)
{
_nop_();
}
}
void delay_ms(unsigned int n)
{
unsigned char i, j;
while(n--)
{
for(i=0; i<250; i++)
{
for(j=0; j<1; j++);
}
}
}
void write_cmd(unsigned char cmd)
{
RS = 0;
RW = 0;
LCD12864 = cmd;
E = 1;
delay_us(5);
E = 0;
}
void write_data(unsigned char dat)
{
RS = 1;
RW = 0;
LCD12864 = dat;
E = 1;
delay_us(5);
E = 0;
}
void init_lcd()
{
delay_ms(15);
write_cmd(0x38);
write_cmd(0x0c);
write_cmd(0x06);
write_cmd(0x01);
delay_ms(2);
}
void display_distance(unsigned int dis)
{
unsigned char i, j;
unsigned char buffer[6] = {0};
buffer[0] = (dis/10000) + '0';
buffer[1] = (dis%10000)/1000 + '0';
buffer[2] = (dis%1000)/100 + '0';
buffer[3] = (dis%100)/10 + '0';
buffer[4] = (dis%10) + '0';
write_cmd(0x80);
write_data('D');
write_data('i');
write_data('s');
write_data('t');
write_data('a');
write_data('n');
write_data('c');
write_data('e');
write_data(':');
write_cmd(0x87);
for(i=0; i<5; i++)
{
if(buffer[i] == '0' && i!=4)
{
continue;
}
for(j=i; j<5; j++)
{
write_data(buffer[j]);
}
break;
}
write_data(' ');
write_data('c');
write_data('m');
}
unsigned int measure_distance()
{
unsigned int dis = 0;
unsigned long time = 0;
TRIG = 0;
delay_us(2);
TRIG = 1;
delay_us(10);
TRIG = 0;
while(ECHO == 0);
time = 0;
while(ECHO == 1)
{
time++;
delay_us(1);
if(time >= 50000)
{
return 0;
}
}
dis = time/58;
return dis;
}
void main()
{
init_lcd();
while(1)
{
distance = measure_distance();
display_distance(distance);
delay_ms(200);
}
}
```
说明:
1. 程序中使用了CD1602液晶显示模块,需要用到P2口作为数据口,P1口的0、1、2号引脚分别接到LCD模块的RS、RW、E引脚上;
2. 程序中使用P3口的2、3号引脚分别接到超声波模块的TRIG、ECHO引脚上;
3. `delay_us`和`delay_ms`函数分别用于产生微秒级和毫秒级的延时;
4. `write_cmd`和`write_data`函数分别用于向LCD模块写入指令和数据;
5. `init_lcd`函数用于初始化LCD模块;
6. `display_distance`函数用于在LCD模块上显示测量到的距离;
7. `measure_distance`函数用于测量距离。
注意事项:
1. 程序中的延时时间需要自行根据实际情况进行调整;
2. 测距时需要将超声波模块的发射引脚(TRIG)先置为低电平2us,再置为高电平10us,最后再置为低电平,等待回波即可;
3. 超声波模块回波的时间(time)单位为微秒,需要将其转换为厘米(cm);
4. 程序中的距离显示格式为"Distance: XXX.XX cm",其中XXX.XX为测量到的距离值,小数点后保留两位。
阅读全文