#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// 定义传感器和执行器的引脚
#define DHTPIN 6 // DHT22传感器的引脚
#define GAS_SENSOR_PIN A0
#define LDR_PIN A1
#define DUST_SENSOR_PIN A2
#define GAS_SWITCH_PIN 2
#define DUST_SWITCH_PIN 3
#define LIGHT_SWITCH_PIN 4
// 定义LED和继电器的连接pin
#define LED_PIN 13
#define RELAY_PIN 12
// 定义传感器类型
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// 实例化LCD显示屏
LiquidCrystal_I2C lcd(0x27, 20, 4);
// 设定阈值
const int TEMP_THRESHOLD = 25; // 温度阈值
const float HUMIDITY_THRESHOLD = 60.0; // 湿度阈值
const int GAS_THRESHOLD = 300; // 假定气体阈值
const int DUST_THRESHOLD = 100; // 粉尘阈值
const int LIGHT_THRESHOLD = 800; // 光敏阈值
void setup() {
pinMode(GAS_SWITCH_PIN, INPUT_PULLUP);
pinMode(DUST_SWITCH_PIN, INPUT_PULLUP);
pinMode(LIGHT_SWITCH_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
pinMode(RELAY_PIN, OUTPUT);
pinMode(LDR_PIN, INPUT);
pinMode(GAS_SENSOR_PIN, INPUT);
pinMode(DUST_SENSOR_PIN, INPUT);
dht.begin();
lcd.init();
lcd.backlight();
digitalWrite(RELAY_PIN, LOW); // 默认关闭风扇
// 初始化串口通信
Serial.begin(9600);
}
void loop() {
// 读取传感器数据
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// 使用三元运算符判断是否读取或显示nan
int gasLevel = digitalRead(GAS_SWITCH_PIN) ? analogRead(GAS_SENSOR_PIN) : -1;
int lightIntensity = digitalRead(LIGHT_SWITCH_PIN) ? analogRead(LDR_PIN) : -1;
int dustDensity = digitalRead(DUST_SWITCH_PIN) ? analogRead(DUST_SENSOR_PIN) : -1;
// 显示传感器数据
displaySensorData(temperature, humidity, gasLevel, lightIntensity, dustDensity);
// 根据阈值控制LED和继电器
checkThresholdsAndControl(temperature, humidity, gasLevel, lightIntensity, dustDensity);
delay(1000); // 更新频率为1秒
}
void displaySensorData(float temperature, float humidity, int gas, int light, int dust) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("T:");
lcd.print(temperature);
lcd.print(" ");
lcd.setCursor(10, 0);
lcd.print("H:");
lcd.print(humidity);
lcd.print(" ");
lcd.setCursor(0, 1);
if (gas >= 0) {
lcd.print("Gas:");
lcd.print(gas);
} else {
lcd.print("Gas: nan");
}
lcd.print(" ");
lcd.setCursor(0, 2);
if (light >= 0) {
lcd.print("Light:");
lcd.print(light);
} else {
lcd.print("Light: nan");
}
lcd.print(" ");
lcd.setCursor(0, 3);
if (dust >= 0) {
lcd.print("Dust:");
lcd.print(dust);
} else {
lcd.print("Dust: nan");
}
lcd.print(" ");
}
void checkThresholdsAndControl(float temperature, float humidity, int gas, int light, int dust) {
// 示例:如果温度大于25度,打开通风
if(temperature > 25) {
digitalWrite(RELAY_PIN, HIGH); // 打开风扇
} else {
digitalWrite(RELAY_PIN, LOW); // 关闭风扇
}
// 根据其它阈值进行类似的控制...
// 高气体浓度或光强度过高,或者粉尘过多时控制LED和风扇
if(gas > 300 || light > 800 || dust > 500) { // 这些阈值需要你根据实际情况调整
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // LED灯闪烁
digitalWrite(RELAY_PIN, HIGH); // 打开风扇
} else {
digitalWrite(LED_PIN, LOW);
}
}