不說了,上代碼,用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