51单片机的温湿度传感器lcd
时间: 2023-11-16 08:05:21 浏览: 84
对于51单片机的温湿度传感器lcd显示,可以采用DHT11传感器和LCD1602液晶屏。具体实现步骤如下:
1. 初始化DHT11传感器和LCD1602液晶屏。
2. 读取DHT11传感器的温湿度数据。
3. 将读取到的温湿度数据显示在LCD1602液晶屏上。
以下是示例代码:
```
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit DHT11 = P1^0; // DHT11传感器数据引脚
sbit RS = P2^0; // LCD1602液晶屏RS引脚
sbit RW = P2^1; // LCD1602液晶屏RW引脚
sbit EN = P2^2; // LCD1602液晶屏EN引脚
void delay(uint x) // 延时函数
{
uint i, j;
for (i = x; i > 0; i--)
for (j = 110; j > 0; j--);
}
void lcd_write_cmd(uchar cmd) // 写命令函数
{
RS = 0;
RW = 0;
P0 = cmd;
EN = 1;
_nop_();
EN = 0;
delay(5);
}
void lcd_write_data(uchar dat) // 写数据函数
{
RS = 1;
RW = 0;
P0 = dat;
EN = 1;
_nop_();
EN = 0;
delay(5);
}
void lcd_init() // 初始化函数
{
lcd_write_cmd(0x38); // 设置16*2显示,5*7点阵,8位数据接口
lcd_write_cmd(0x0c); // 开显示,无光标,不闪烁
lcd_write_cmd(0x06); // 光标右移,字符不移动
lcd_write_cmd(0x01); // 清屏
}
void dht11_start() // 启动DHT11传感器
{
DHT11 = 0;
delay(20);
DHT11 = 1;
delay(30);
}
uchar dht11_response() // 接收DHT11传感器响应信号
{
uchar i;
for (i = 0; i < 200; i++)
{
if (DHT11 == 0)
{
delay(30);
if (DHT11 == 1)
break;
}
}
if (i >= 200)
return 1;
else
return 0;
}
uchar dht11_read_byte() // 读取DHT11传感器数据
{
uchar i, dat = 0;
for (i = 0; i < 8; i++)
{
while (DHT11 == 0);
delay(30);
if (DHT11 == 1)
dat |= (1 << (7 - i));
while (DHT11 == 1);
}
return dat;
}
void main()
{
uchar humi, temp, humi_int, humi_dec, temp_int, temp_dec;
lcd_init();
while (1)
{
dht11_start();
if (dht11_response() == 0)
{
humi = dht11_read_byte();
humi_int = humi / 10;
humi_dec = humi % 10;
temp = dht11_read_byte();
temp_int = temp / 10;
temp_dec = temp % 10;
lcd_write_cmd(0x80); // 光标移动到第一行第一列
lcd_write_data('H');
lcd_write_data('u');
lcd_write_data('m');
lcd_write_data('i');
lcd_write_data(':');
lcd_write_data(humi_int + '0');
lcd_write_data('.');
lcd_write_data(humi_dec + '0');
lcd_write_data('%');
lcd_write_cmd(0x8c); // 光标移动到第一行第九列
lcd_write_data('T');
lcd_write_data('e');
lcd_write_data('m');
lcd_write_data('p');
lcd_write_data(':');
lcd_write_data(temp_int + '0');
lcd_write_data('.');
lcd_write_data(temp_dec + '0');
lcd_write_data('C');
}
delay(1000);
}
}
```
阅读全文