不说了,上代码,用arduino实现esp8266代码
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <SimpleDHT.h> // 定义DHT11引脚 // VCC: 5V or 3V // GND: GND // DATA: 2 int pinDHT11 = D4; SimpleDHT11 dht11(pinDHT11); // read without samples. byte temperature = 0; byte humidity = 0; int err = SimpleDHTErrSuccess; // 定义LED引脚 #define LED_PIN 5 // 创建Web服务器对象 ESP8266WebServer server(80); // 处理根目录请求的函数 void handleRoot() { // 获取LED状态 String ledState = digitalRead(LED_PIN) == HIGH ? "OFF" : "ON"; // 生成HTML页面内容 String html = "<html><head><title>DHT11 and LED Control</title></head><body>"; html += "<h1>DHT11 and LED Control</h1>"; html += "<p>Temperature: "; html += (int)temperature; html += " *C</p>"; html += "<p>Humidity: "; html += (int)humidity; html += " %</p>"; html += "<p>LED State: "; html += ledState; html += "</p>"; html += "<form method=\"POST\" action=\"/led\">"; html += "<button type=\"submit\" name=\"state\" value=\"on\">Turn On</button>"; html += "<button type=\"submit\" name=\"state\" value=\"off\">Turn Off</button>"; html += "</form>"; html += "</body></html>"; // 发送HTML页面内容 server.send(200, "text/html", html); } // 处理LED控制请求的函数 void handleLed() { // 获取按钮状态 String state = server.arg("state"); // 根据按钮状态控制LED灯 if (state == "on") { digitalWrite(LED_PIN, LOW); } else if (state == "off") { digitalWrite(LED_PIN, HIGH); } // 返回根目录 server.sendHeader("Location", "/"); server.send(302, "text/plain", ""); } void setup() { // 初始化串口 Serial.begin(9600); while (!Serial) {} // 初始化LED引脚 pinMode(LED_PIN, OUTPUT); delay(20); digitalWrite(LED_PIN, HIGH); // 连接WiFi网络 WiFi.begin("litianmenzhenbu", "LT12345678"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(1000); } Serial.println(""); Serial.println("WiFi connected"); // 注册请求处理函数 server.on("/", handleRoot); server.on("/led", handleLed); // 启动Web服务器 server.begin(); } void loop() { for (int i=0;i<1000;i++) { delay(1); // 处理Web请求 server.handleClient(); } // 读取温湿度 if ((err = dht11.read(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) { Serial.print("Read DHT11 failed, err="); Serial.println(err);//delay(1000); //return; } // Serial.print("Sample OK: "); // Serial.print((int)temperature); Serial.print(" *C, "); // Serial.print((int)humidity); Serial.println(" H"); //// // DHT11 sampling rate is 1HZ. // delay(1500); }
效果:
需要使用360防火墙找到esp8266的ip地址 , 打开浏览器输入ip即可控制
DHT11 and LED Control
Temperature: 25 *C
Humidity: 59 %
LED State: OFF
标签:LED,esp8266,PIN,int,温湿度,智能家居,server,html,Serial From: https://www.cnblogs.com/LiuXinyu12378/p/17416442.html