esp8266 dht11

#include #include #include #include “DHT.h” // ====== CẤU HÌNH ====== const char* WIFI_SSID = “Loi”; const char* WIFI_PASSWORD = “123456789”; // WP endpoint theo plugin const char* POST_URL = “https://dientu.vn/wp-json/esp32/v1/telemetry?key=dientuVN_2025_secretKey123”; // DHT11 trên GPIO14 (D5) #define DHTPIN 14 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); // LED cảnh báo (LED on-board NodeMCU = D4 = GPIO2) #define LED_PIN 2 // Chu kỳ gửi const unsigned long POST_INTERVAL_MS = 15000; // Backoff tối đa khi lỗi const unsigned long MAX_BACKOFF_MS = 60000; unsigned long lastPost = 0; unsigned long backoff = 0; void waitBlink(unsigned long ms) { unsigned long t0 = millis(); while (millis() – t0 < ms) delay(10); } void connectWiFi() { if (WiFi.status() == WL_CONNECTED) return; WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("WiFi connecting"); uint32_t t0 = millis(); // LED nhấp nháy khi chưa kết nối while (WiFi.status() != WL_CONNECTED) { digitalWrite(LED_PIN, LOW); // LED sáng delay(200); digitalWrite(LED_PIN, HIGH); // LED tắt delay(300); Serial.print("."); if (millis() - t0 > 20000) { // timeout 20s Serial.println(“\n⚠️ WiFi FAIL → restart”); ESP.restart(); } } Serial.printf(“\n✅ WiFi OK, IP: %s\n”, WiFi.localIP().toString().c_str()); digitalWrite(LED_PIN, HIGH); // LED tắt khi đã kết nối } bool postTelemetry(float tempC, float hum) { std::unique_ptr client(new BearSSL::WiFiClientSecure); client->setInsecure(); // test nhanh; khi chạy thật => dùng setTrustAnchors(…) HTTPClient http; if (!http.begin(*client, POST_URL)) { Serial.println(“HTTP begin failed”); return false; } http.addHeader(“Content-Type”, “application/json”); String payload = String(“{\”temperature\”:”) + String(tempC, 1) + String(“,\”humidity\”:”) + String(hum, 1) + String(“,\”device\”:\”esp8266-01\”}”); int code = http.POST(payload); Serial.printf(“POST code=%d\n”, code); if (code > 0) { String resp = http.getString(); Serial.println(resp); } http.end(); return (code >= 200 && code < 300); } void setup() { Serial.begin(115200); delay(100); dht.begin(); pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, HIGH); // LED off ban đầu connectWiFi(); } void loop() { // Nếu mất WiFi thì cảnh báo + tự kết nối lại if (WiFi.status() != WL_CONNECTED) { Serial.println("⚠️ WiFi lost → reconnecting..."); connectWiFi(); } unsigned long now = millis(); unsigned long due = (backoff == 0) ? POST_INTERVAL_MS : backoff; if (now - lastPost < due) return; lastPost = now; float h = dht.readHumidity(); float t = dht.readTemperature(); if (isnan(h) || isnan(t)) { Serial.println("❌ DHT read failed"); return; } bool ok = postTelemetry(t, h); if (ok) { backoff = 0; } else { backoff = (backoff == 0) ? 5000 : backoff * 2; if (backoff > MAX_BACKOFF_MS) backoff = MAX_BACKOFF_MS; Serial.printf(“⚠️ POST fail → backoff %lu ms\n”, backoff); } }

Để lại một bình luận