#include #include #include #include const char* WIFI_SSID = "testwifi"; const char* WIFI_PASS = "12345678"; #define DHTPIN 4 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); AsyncWebServer server(80); AsyncWebSocket ws("/ws"); unsigned long lastSend = 0; bool streaming = false; const char HTML_PAGE[] PROGMEM = R"rawhtml( DHT22 Monitor

Temperature and Humidity Monitoring

Waiting for data...
60° 40° 20° -10°
--.-°C
Temperature
--.-%
Humidity
Press Start to begin reading sensor data.
)rawhtml"; void onWsEvent(AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) { if (type == WS_EVT_CONNECT) { Serial.printf("Client #%u connected\n", client->id()); } else if (type == WS_EVT_DISCONNECT) { Serial.printf("Client #%u disconnected\n", client->id()); } else if (type == WS_EVT_DATA) { AwsFrameInfo* info = (AwsFrameInfo*)arg; if (info->final && info->index == 0 && info->len == len) { String msg = ""; for (size_t i = 0; i < len; i++) msg += (char)data[i]; if (msg.indexOf("start") > 0) { streaming = true; Serial.println("Streaming: ON"); } else if (msg.indexOf("stop") > 0) { streaming = false; Serial.println("Streaming: OFF"); } } } } void setup() { Serial.begin(115200); dht.begin(); WiFi.begin(WIFI_SSID, WIFI_PASS); Serial.print("Connecting to WiFi"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("\nConnected! IP: " + WiFi.localIP().toString()); ws.onEvent(onWsEvent); server.addHandler(&ws); server.on("/", HTTP_GET, [](AsyncWebServerRequest* req) { req->send_P(200, "text/html", HTML_PAGE); }); server.begin(); Serial.println("Open browser: http://" + WiFi.localIP().toString()); } void loop() { ws.cleanupClients(); if (streaming && millis() - lastSend >= 2000) { lastSend = millis(); float h = dht.readHumidity(); float t = dht.readTemperature(); if (!isnan(h) && !isnan(t)) { String json = "{\"temp\":" + String(t,1) + ",\"hum\":" + String(h,1) + "}"; ws.textAll(json); Serial.println("Sent: " + json); } } }