51单片机代码 在LCD1602上显示HX711的数值
时间: 2024-05-03 09:17:44 浏览: 98
以下是51单片机代码,可以在LCD1602上显示HX711的数值:
```c
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit RS = P2^0; //LCD1602接口定义
sbit RW = P2^1;
sbit EN = P2^2;
uchar code table[] = "Weight: ";
void delay1ms(uint i) //1ms延时函数
{
uint j, k;
for (j = i; j > 0; j--)
for (k = 110; k > 0; k--);
}
void InitLcd() //初始化LCD1602
{
delay1ms(15);
sendcmd(0x38);
delay1ms(5);
sendcmd(0x38);
delay1ms(5);
sendcmd(0x38);
delay1ms(5);
sendcmd(0x0C);
delay1ms(5);
sendcmd(0x01);
delay1ms(5);
}
void sendcmd(uchar command) //发送指令到LCD1602
{
RS = 0;
RW = 0;
P0 = command;
EN = 1;
_nop_();
_nop_();
EN = 0;
}
void senddata(uchar dat) //发送数据到LCD1602
{
RS = 1;
RW = 0;
P0 = dat;
EN = 1;
_nop_();
_nop_();
EN = 0;
}
void main()
{
uchar weight[5];
uint val;
InitLcd();
while (1)
{
val = read_hx711(); //读取HX711的数值
val /= 100; //将数值除以100
weight[4] = val % 10 + '0'; //个位数值
weight[3] = val / 10 % 10 + '0'; //十位数值
weight[2] = '.'; //小数点
weight[1] = val / 100 % 10 + '0'; //百位数值
weight[0] = ' '; //空格
sendcmd(0x80); //设置光标位置为第一行第一列
for (int i = 0; i < 8; i++)
senddata(table[i]); //显示“Weight:”
for (int i = 0; i < 5; i++)
senddata(weight[i]); //显示数值
}
}
uint read_hx711() //读取HX711的数据并返回数值
{
uint val = 0;
uchar i;
P1 = 0x10; //将PD_SCK置高
delay1ms(1);
P1 &= 0xEF; //将PD_SCK置低
while (DOUT);
for (i = 0; i < 24; i++)
{
P1 = 0x10; //将PD_SCK置高
val <<= 1;
delay1ms(1);
P1 &= 0xEF; //将PD_SCK置低
if (DOUT)
val++;
}
P1 = 0x10; //将PD_SCK置高
delay1ms(1);
P1 &= 0xEF; //将PD_SCK置低
return val;
}
```
注意:以上代码仅为示例,需要根据具体的硬件连接和HX711的驱动程序进行修改。
阅读全文