51单片机控制dht11并用lcd1602显示的代码
时间: 2023-09-01 17:07:14 浏览: 228
下面是一个基于51单片机控制DHT11并用LCD1602显示的简单代码:
```c
#include <reg51.h>
#include <stdio.h>
#include <intrins.h>
#define DHT11_PIN P2_0 // DHT11数据线连接的单片机引脚
#define LCD_RS P0_0 // LCD1602的RS引脚
#define LCD_RW P0_1 // LCD1602的RW引脚
#define LCD_EN P0_2 // LCD1602的EN引脚
#define LCD_DAT P1 // LCD1602的数据线
unsigned char dht11_data[5];
void delay(unsigned int x) {
unsigned int i, j;
for (i = 0; i < x; i++) {
for (j = 0; j < 125; j++);
}
}
void lcd_write_cmd(unsigned char cmd) {
LCD_RS = 0;
LCD_RW = 0;
LCD_EN = 0;
LCD_DAT = cmd;
delay(1);
LCD_EN = 1;
delay(1);
LCD_EN = 0;
delay(1);
}
void lcd_write_data(unsigned char dat) {
LCD_RS = 1;
LCD_RW = 0;
LCD_EN = 0;
LCD_DAT = dat;
delay(1);
LCD_EN = 1;
delay(1);
LCD_EN = 0;
delay(1);
}
void lcd_init() {
lcd_write_cmd(0x38);
lcd_write_cmd(0x0c);
lcd_write_cmd(0x06);
lcd_write_cmd(0x01);
}
void lcd_display_string(unsigned char x, unsigned char y, unsigned char *p) {
unsigned char addr;
if (y == 0) {
addr = 0x80 + x;
} else {
addr = 0xc0 + x;
}
lcd_write_cmd(addr);
while (*p) {
lcd_write_data(*p++);
}
}
void dht11_init() {
DHT11_PIN = 1;
delay(500);
}
unsigned char dht11_read_byte() {
unsigned char i, dat;
dat = 0;
for (i = 0; i < 8; i++) {
while (!DHT11_PIN);
delay(30);
if (DHT11_PIN == 0) {
dat <<= 1;
} else {
dat = (dat << 1) | 0x01;
}
while (DHT11_PIN);
}
return dat;
}
void dht11_read_data() {
unsigned char i, checksum;
DHT11_PIN = 0;
delay(20);
DHT11_PIN = 1;
while (DHT11_PIN);
while (!DHT11_PIN);
while (DHT11_PIN);
for (i = 0; i < 5; i++) {
dht11_data[i] = dht11_read_byte();
}
DHT11_PIN = 1;
checksum = dht11_data[0] + dht11_data[1] + dht11_data[2] + dht11_data[3];
if (checksum != dht11_data[4]) {
lcd_display_string(0, 1, "Checksum Error!");
} else {
lcd_display_string(0, 1, "Temp:");
lcd_write_data(dht11_data[0] / 10 + '0');
lcd_write_data(dht11_data[0] % 10 + '0');
lcd_write_data('.');
lcd_write_data(dht11_data[1] / 10 + '0');
lcd_write_data(dht11_data[1] % 10 + '0');
lcd_write_data('C');
lcd_display_string(8, 1, "Hum:");
lcd_write_data(dht11_data[2] / 10 + '0');
lcd_write_data(dht11_data[2] % 10 + '0');
lcd_write_data('.');
lcd_write_data(dht11_data[3] / 10 + '0');
lcd_write_data(dht11_data[3] % 10 + '0');
lcd_write_data('%');
}
}
void main() {
lcd_init();
lcd_display_string(0, 0, "DHT11 Temperature");
lcd_display_string(0, 1, "and Humidity Test");
delay(2000);
while (1) {
dht11_init();
dht11_read_data();
delay(2000);
}
}
```
这个代码使用了51单片机来读取DHT11传感器的温度和湿度值,并通过LCD1602显示出来。具体实现过程中,我们需要先初始化LCD1602,然后在主函数中循环读取DHT11传感器的数据,并将温度和湿度值显示到LCD1602上。需要注意的是,DHT11传感器的数据读取过程是比较复杂的,需要按照一定的时序和协议进行操作。
阅读全文