51接超声波测距1602显示,精度显示小数点后两位串口助手显示超声波数据C语言代码
时间: 2023-03-27 18:01:11 浏览: 59
以下是 C 语言代码,用于实现 51 接超声波测距 1602 显示,精度显示小数点后两位,同时串口助手显示超声波数据:
#include <reg51.h>
#include <intrins.h>
#define LCD1602_DB P
sbit LCD1602_RS = P2^6;
sbit LCD1602_RW = P2^5;
sbit LCD1602_E = P2^7;
sbit Trig = P3^5;
sbit Echo = P3^2;
unsigned int distance;
void delay(unsigned int i)
{
while(i--);
}
void LCD1602_WriteCmd(unsigned char cmd)
{
LCD1602_RS = ;
LCD1602_RW = ;
LCD1602_E = ;
LCD1602_DB = cmd;
delay(5);
LCD1602_E = 1;
delay(5);
LCD1602_E = ;
}
void LCD1602_WriteData(unsigned char dat)
{
LCD1602_RS = 1;
LCD1602_RW = ;
LCD1602_E = ;
LCD1602_DB = dat;
delay(5);
LCD1602_E = 1;
delay(5);
LCD1602_E = ;
}
void LCD1602_Init()
{
LCD1602_WriteCmd(x38);
LCD1602_WriteCmd(xc);
LCD1602_WriteCmd(x06);
LCD1602_WriteCmd(x01);
}
void LCD1602_Display(unsigned char x, unsigned char y, unsigned char *str)
{
unsigned char addr;
if(y == )
addr = x80 + x;
else
addr = xc + x;
LCD1602_WriteCmd(addr);
while(*str)
{
LCD1602_WriteData(*str++);
}
}
void Init_Timer()
{
TMOD |= x01;
TH = ;
TL = ;
TR = 1;
}
void Timer_ISR() interrupt 1
{
TH = ;
TL = ;
Trig = 1;
delay(10);
Trig = ;
while(!Echo);
TR = ;
distance = (unsigned int)(TH << 8) | TL;
distance = distance / 58;
LCD1602_Display(, , "Distance:");
LCD1602_Display(9, , (unsigned char *)(distance / 100 + x30));
LCD1602_Display(10, , (unsigned char *)(distance % 100 / 10 + x30));
LCD1602_Display(11, , (unsigned char *)(distance % 10 + x30));
}
void main()
{
LCD1602_Init();
Init_Timer();
while(1);
}
阅读全文
相关推荐









