#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <DHT.h>
#define DHTPIN 4 // Pin where the DHT11 data pin is connected
#define DHTTYPE DHT11 // Define the type of DHT sensor
// Set up the WiFi credentials
const char* ssid = "Your_SSID";
const char* password = "Your_PASSWORD";
// Set up the DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Create an AsyncWebServer object on port 80
AsyncWebServer server(80);
void setup() {
// Start serial communication
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize the DHT sensor
dht.begin();
// Serve a simple HTML page to show the temperature
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
String html = "<!DOCTYPE html><html><head><title>ESP32 Temperature</title>";
html += "<style>body {background-color: black; color: white; font-family: Arial, sans-serif; text-align: center; margin-top: 20%;}</style>";
html += "<h1>Real-Time Temperature</h1>";
html += "<p>Temperature: ";
// Get temperature from the DHT11 sensor
float temp = dht.readTemperature();
if (isnan(temp)) {
html += "Failed to read temperature!";
} else {
html += String(temp) + " ℃";
}
html += "</p></body></html>";
// Send the HTML page
request->send(200, "text/html", html);
});
// Start the server
server.begin();
}
void loop() {
// Nothing needed in loop, the server runs in the background
}