帮我写个程序:读取DHT11 温湿度传感器数值,并在LCD 屏幕实时 显示。每间隔5 秒通过串口向电脑发送一次温湿度数据。温度超过设定阈值,小灯1 呼吸;湿度超过阈值,小灯2 呼吸。没超 过是,小灯熄灭,每隔20 秒将温湿度保存到EEPROM 中
时间: 2023-06-11 16:08:05 浏览: 88
温湿度传感器DHT11的显示程序
以下是一个基于Arduino的程序,可以实现读取DHT11传感器数值,并在LCD屏幕上实时显示。此外,每间隔5秒通过串口向电脑发送一次温湿度数据。如果温度或湿度超过设定阈值,小灯1或小灯2将呼吸,如果没有超过阈值,则小灯将熄灭。每隔20秒,程序还将温湿度保存到EEPROM中。请根据实际情况进行修改。
```
#include <LiquidCrystal.h>
#include <EEPROM.h>
#include <DHT.h>
#define DHTPIN 2 // DHT11传感器连接到Arduino的2号引脚
#define DHTTYPE DHT11 // DHT11传感器类型
#define LED1 5 // 小灯1连接到Arduino的5号引脚
#define LED2 6 // 小灯2连接到Arduino的6号引脚
#define TEMP_THRESHOLD 25 // 温度阈值
#define HUMIDITY_THRESHOLD 60 // 湿度阈值
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal lcd(7, 8, 9, 10, 11, 12); //LCD屏幕连接到Arduino的引脚
void setup() {
Serial.begin(9600);
dht.begin();
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
lcd.begin(16, 2);
lcd.print("Temperature: ");
}
void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print(" % ");
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C ");
delay(5000);
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
if (temperature > TEMP_THRESHOLD) {
breathe(LED1);
} else {
digitalWrite(LED1, LOW);
}
if (humidity > HUMIDITY_THRESHOLD) {
breathe(LED2);
} else {
digitalWrite(LED2, LOW);
}
delay(15000);
saveToEEPROM(temperature, humidity);
}
void breathe(int ledPin) {
for (int i = 0; i < 255; i++) {
analogWrite(ledPin, i);
delay(5);
}
for (int i = 255; i >= 0; i--) {
analogWrite(ledPin, i);
delay(5);
}
}
void saveToEEPROM(float temperature, float humidity) {
int addr = 0;
EEPROM.put(addr, temperature);
addr += sizeof(temperature);
EEPROM.put(addr, humidity);
addr += sizeof(humidity);
EEPROM.commit();
}
```
阅读全文