#include <WiFi.h>
#include <WebServer.h>
#include <DHTesp.h>
// ESP32-S3引脚配置
#define DHTPIN 4 // DHT22数据引脚
#define LIGHT_SENSOR_PIN 1 // 光敏电阻(GPIO1,ADC1_CH0)
#define RAIN_SENSOR_PIN 2 // 雨水检测(GPIO2,ADC1_CH1)
#define MOTOR_PIN1 8 // 电机控制1
#define MOTOR_PIN2 9 // 电机控制2
// 设备状态
bool isExtended = false;
bool autoMode = true;
float lightThreshold = 1500; // 光照阈值(Wokwi光敏电阻模拟值范围0-4095)
// 传感器对象
DHTesp dht;
// WiFi配置(Wokwi专用配置)
const char* ssid = "Wokwi-GUEST";
const char* password = "";
WebServer server(80);
void setup() {
Serial.begin(115200);
// 初始化DHT22
dht.setup(DHTPIN, DHTesp::DHT22);
// 设置电机控制引脚
pinMode(MOTOR_PIN1, OUTPUT);
pinMode(MOTOR_PIN2, OUTPUT);
stopMotor();
// 连接WiFi(Wokwi自动连接)
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// 启动Web服务器
server.on("/", handleRoot);
server.on("/control", handleControl);
server.begin();
}
void loop() {
server.handleClient();
if(autoMode) {
TempAndHumidity data = dht.getTempAndHumidity();
int lightValue = analogRead(LIGHT_SENSOR_PIN);
int rainValue = analogRead(RAIN_SENSOR_PIN);
Serial.print("Light: ");
Serial.print(lightValue);
Serial.print(" | Rain: ");
Serial.print(rainValue);
Serial.print(" | Humidity: ");
Serial.println(data.humidity);
// 自动控制逻辑
if (rainValue > 2000 || data.humidity > 80) {
retractClothesRail();
} else if (lightValue < lightThreshold) {
extendClothesRail();
}
}
delay(1000);
}
// 电机控制函数
void extendClothesRail() {
if(!isExtended) {
digitalWrite(MOTOR_PIN1, HIGH);
digitalWrite(MOTOR_PIN2, LOW);
delay(2000); // 模拟电机运行时间
stopMotor();
isExtended = true;
Serial.println("Clothes rail extended");
}
}
void retractClothesRail() {
if(isExtended) {
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, HIGH);
delay(2000);
stopMotor();
isExtended = false;
Serial.println("Clothes rail retracted");
}
}
void stopMotor() {
digitalWrite(MOTOR_PIN1, LOW);
digitalWrite(MOTOR_PIN2, LOW);
}
// Web控制界面
void handleRoot() {
String html = R"(
<html><body>
<h1>ESP32-S3 Smart Clothes Rail</h1>
<p>状态:)" + String(isExtended ? "展开" : "收回") + R"(</p>
<p>模式:)" + String(autoMode ? "自动" : "手动") + R"(</p>
<button onclick="location.href='/control?cmd=extend'">展开</button>
<button onclick="location.href='/control?cmd=retract'">收回</button>
<button onclick="location.href='/control?cmd=auto'">切换模式</button>
</body></html>)";
server.send(200, "text/html", html);
}
void handleControl() {
String cmd = server.arg("cmd");
if(cmd == "extend") {
extendClothesRail();
} else if(cmd == "retract") {
retractClothesRail();
} else if(cmd == "auto") {
autoMode = !autoMode;
}
handleRoot();
}