#include <DHT.h>
// 定义引脚
#define DHTPIN 2 // DHT22数据引脚
#define DHTTYPE DHT22 // DHT传感器类型
#define FAN_PIN 3 // 风扇控制引脚
#define BUTTON_PIN 4 // 按键引脚
// 温度阈值
#define TEMP_THRESHOLD 28 // 自动启动温度(℃)
// 系统状态变量
enum SystemMode { AUTO, MANUAL };
SystemMode currentMode = AUTO; // 初始为自动模式
bool fanState = false; // 风扇状态
// 按键相关变量
unsigned long buttonPressTime = 0;
bool buttonActive = false;
const long longPressDuration = 3000; // 长按3秒
// 初始化DHT传感器
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
// 设置引脚模式
pinMode(FAN_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // 使用内部上拉电阻
// 初始化风扇状态
digitalWrite(FAN_PIN, LOW);
// 启动DHT传感器
dht.begin();
Serial.println("Smart Fan Control System");
Serial.println("Initialized in AUTO mode");
}
void loop() {
// put your main code here, to run repeatedly:
// 1. 读取温度数据
float temperature = dht.readTemperature();
// 2. 处理按键输入
handleButtonInput();
// 3. 根据模式控制风扇
if (currentMode == AUTO) {
// 自动模式:基于温度控制
if (temperature >= TEMP_THRESHOLD) {
fanState = true;
} else {
fanState = false;
}
}
// 4. 更新风扇状态
digitalWrite(FAN_PIN, fanState ? HIGH : LOW);
// 5. 串口输出状态信息
printSystemStatus(temperature);
delay(100); // 短延时保持响应速度
}
// 处理按键输入函数
void handleButtonInput() {
// 读取按键状态 (按下时为LOW,因为使用上拉)
int buttonState = digitalRead(BUTTON_PIN);
// 按键按下
if (buttonState == LOW) {
if (!buttonActive) {
// 记录按下时间
buttonPressTime = millis();
buttonActive = true;
}
// 检测长按(3秒)
if (buttonActive && (millis() - buttonPressTime > longPressDuration)) {
// 切换模式
currentMode = (currentMode == AUTO) ? MANUAL : AUTO;
Serial.print("Mode changed to: ");
Serial.println(currentMode == AUTO ? "AUTO" : "MANUAL");
// 重置按键状态
buttonActive = false;
// 如果是手动模式,切换风扇状态
if (currentMode == MANUAL) {
fanState = !fanState;
}
// 防止重复触发
delay(300);
}
}
// 按键释放
else if (buttonState == HIGH) {
if (buttonActive) {
// 短按处理(仅手动模式下有效)
if (currentMode == MANUAL && (millis() - buttonPressTime < longPressDuration)) {
fanState = !fanState; // 切换风扇状态
Serial.print("Fan manually ");
Serial.println(fanState ? "STARTED" : "STOPPED");
}
buttonActive = false;
}
}
}
// 打印系统状态函数
void printSystemStatus(float temp) {
static unsigned long lastUpdate = 0;
// 每秒更新一次状态显示
if (millis() - lastUpdate > 1000) {
Serial.println("\n--- System Status ---");
Serial.print("Mode: ");
Serial.println(currentMode == AUTO ? "AUTO" : "MANUAL");
Serial.print("Temperature: ");
Serial.print(temp);
Serial.println("°C");
Serial.print("Fan: ");
Serial.println(fanState ? "RUNNING" : "STOPPED");
Serial.print("Action: ");
if (currentMode == AUTO) {
if (temp >= TEMP_THRESHOLD) {
Serial.println("Temperature ABOVE threshold - Fan ON");
} else {
Serial.println("Temperature BELOW threshold - Fan OFF");
}
}
lastUpdate = millis();
}
}