STC89C52dht11温湿度传感器lcd
时间: 2024-12-21 10:06:24 浏览: 11
STC89C52是一种常用的51系列单片机,DHT11是一种常见的温湿度传感器,而LCD则是液晶显示器的缩写。将这三者结合起来,可以实现一个简单的温湿度监测系统。
### 硬件连接
1. **STC89C52与DHT11的连接**
- VCC接5V电源
- GND接地
- DATA接单片机的某一个IO口(如P1.0)
2. **STC89C52与LCD的连接**
- VSS接地
- VDD接5V电源
- V0接电位器中间引脚,用于调节对比度
- RS接单片机的某一个IO口(如P2.0)
- RW接地
- E接单片机的某一个IO口(如P2.1)
- D4-D7分别接单片机的某一个IO口(如P2.2-P2.5)
### 软件编程
1. **初始化DHT11和LCD**
2. **读取DHT11的数据**
3. **将数据输出到LCD显示**
以下是一个简单的示例代码:
```c
#include <reg52.h>
#include <stdio.h>
#define DHT11_PIN P1_0
#define LCD_RS P2_0
#define LCD_E P2_1
#define LCD_D4 P2_2
#define LCD_D5 P2_3
#define LCD_D6 P2_4
#define LCD_D7 P2_5
void delay(unsigned int time) {
unsigned int i, j;
for(i = 0; i < time; i++)
for(j = 0; j < 1275; j++);
}
void lcd_cmd(unsigned char cmd) {
LCD_RS = 0;
LCD_D4 = (cmd >> 4) & 0x01;
LCD_D5 = (cmd >> 5) & 0x01;
LCD_D6 = (cmd >> 6) & 0x01;
LCD_D7 = (cmd >> 7) & 0x01;
LCD_E = 1;
delay(1);
LCD_E = 0;
LCD_D4 = cmd & 0x01;
LCD_D5 = (cmd >> 1) & 0x01;
LCD_D6 = (cmd >> 2) & 0x01;
LCD_D7 = (cmd >> 3) & 0x01;
LCD_E = 1;
delay(1);
LCD_E = 0;
}
void lcd_data(unsigned char dat) {
LCD_RS = 1;
LCD_D4 = (dat >> 4) & 0x01;
LCD_D5 = (dat >> 5) & 0x01;
LCD_D6 = (dat >> 6) & 0x01;
LCD_D7 = (dat >> 7) & 0x01;
LCD_E = 1;
delay(1);
LCD_E = 0;
LCD_D4 = dat & 0x01;
LCD_D5 = (dat >> 1) & 0x01;
LCD_D6 = (dat >> 2) & 0x01;
LCD_D7 = (dat >> 3) & 0x01;
LCD_E = 1;
delay(1);
LCD_E = 0;
}
void lcd_init() {
lcd_cmd(0x28);
lcd_cmd(0x0C);
lcd_cmd(0x06);
lcd_cmd(0x01);
delay(10);
}
void lcd_display(unsigned char *str) {
while(*str) {
lcd_data(*str++);
}
}
unsigned char read_dht11() {
unsigned char i, j, data = 0;
DHT11_PIN = 0;
delay(18000);
DHT11_PIN = 1;
delay(30);
DHT11_PIN = 1;
delay(80);
if(DHT11_PIN == 0) {
delay(80);
for(i = 0; i < 8; i++) {
delay(80);
data <<= 1;
if(DHT11_PIN == 1) {
data |= 1;
}
delay(80);
}
}
return data;
}
void main() {
unsigned char temp, hum;
lcd_init();
lcd_display("Temp:");
lcd_cmd(0xC0);
lcd_display("Hum:");
while(1) {
temp = read_dht11();
lcd_cmd(0xC0);
lcd_data(temp + '0');
hum = read_dht11();
lcd_cmd(0xC0 + 4);
lcd_data(hum + '0');
delay(1000);
}
}
```
### 代码说明
1. **延时函数**:`delay`函数用于产生延时。
2. **LCD命令和数据写入函数**:`lcd_cmd`用于发送命令,`lcd_data`用于发送数据。
3. **LCD初始化函数**:`lcd_init`用于初始化LCD。
4. **LCD显示函数**:`lcd_display`用于显示字符串。
5. **读取DHT11数据函数**:`read_dht11`用于读取DHT11的温湿度数据。
6. **主函数**:`main`函数初始化LCD并循环读取温湿度数据并显示。
阅读全文