51单片机超声波测距l用cd1602显示程序
时间: 2023-08-30 20:12:11 浏览: 86
以下是一个简单的51单片机超声波测距并用CD1602液晶显示的程序:
```c
#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit RS=P2^0; //定义1602端口
sbit RW=P2^1;
sbit EN=P2^2;
sbit Trig=P1^0; //定义超声波端口
sbit Echo=P1^1;
uchar dat[4]; //定义显示数据数组
void InitLcd(); //函数声明
void WriteCommand(uchar com);
void WriteData(uchar date);
void WriteString(uchar *s);
void DelayMS(uint ms);
void DelayUS(uint us);
void SendPulse();
uint MeasureDistance();
void main()
{
uint distance;
InitLcd();
WriteString("Distance:");
while(1)
{
distance = MeasureDistance();
dat[3] = distance%10+'0'; //个位数字
dat[2] = distance/10%10+'0'; //十位数字
dat[1] = distance/100%10+'0';//百位数字
dat[0] = distance/1000+'0'; //千位数字
WriteCommand(0x80+0x40+0); //液晶第二行第一列开始
WriteData(dat[0]);
WriteData(dat[1]);
WriteData(dat[2]);
WriteData(dat[3]);
WriteString(" cm");
DelayMS(50);
}
}
void InitLcd() //初始化液晶
{
WriteCommand(0x38);
WriteCommand(0x0c);
WriteCommand(0x06);
WriteCommand(0x01);
}
void WriteCommand(uchar com) //写入命令
{
RS = 0;
RW = 0;
P0 = com;
EN = 1;
DelayMS(5);
EN = 0;
}
void WriteData(uchar date) //写入数据
{
RS = 1;
RW = 0;
P0 = date;
EN = 1;
DelayMS(5);
EN = 0;
}
void WriteString(uchar *s) //写入字符串
{
while(*s)
{
WriteData(*s++);
}
}
void DelayMS(uint ms) //延时函数
{
uchar i, j;
for(i=ms; i>0; i--)
{
for(j=110; j>0; j--);
}
}
void DelayUS(uint us) //微秒延时函数
{
while(us--);
}
void SendPulse() //发送超声波脉冲
{
Trig = 1;
DelayUS(10);
Trig = 0;
}
uint MeasureDistance() //测量距离
{
uint distance;
SendPulse();
while(Echo == 0);
TH1 = 0;
TL1 = 0;
TR1 = 1;
while(Echo == 1);
TR1 = 0;
distance = (TH1<<8 | TL1)/58;
return distance;
}
```
该程序使用了定时器1来测量超声波回响时间,然后计算距离并将其显示在CD1602液晶上。程序中还包括了常用的LCD1602初始化、写入命令、写入数据、写入字符串等函数。
阅读全文