/* ESP32 HTTP IoT Server Example for Wokwi.com
https://wokwi.com/projects/320964045035274834
To test, you need the Wokwi IoT Gateway, as explained here:
https://docs.wokwi.com/guides/esp32-wifi#the-private-gateway
Then start the simulation, and open http://localhost:9080
in another browser tab.
Note that the IoT Gateway requires a Wokwi Club subscription.
To purchase a Wokwi Club subscription, go to https://wokwi.com/club
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <uri/UriBraces.h>
#include <DHT.h>
#define DHTPIN 26
#define DHTTYPE DHT22
DHT dht (DHTPIN, DHTTYPE);
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
WebServer server(80);
void handleRoot() {
// char msg[1500];
// snprintf(msg, 1500,
String response = R"(
<!DOCTYPE html><html>
<head>
<meta http-equiv='refresh' content='4'/>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.2/css/all.css' integrity='sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr' crossorigin='anonymous'>
<title>ESP32 DHT Server</title>
<style>
html { font-family: Arial; display: inline-block; margin: 0px auto; text-align: center;}
h2 { font-size: 3.0rem; }
p { font-size: 3.0rem; }
.units { font-size: 1.2rem; }
.dht-labels{ font-size: 1.5rem; vertical-align:middle; padding-bottom: 15px;}
</style>
</head>
<body>
<h2>ESP32 DHT Server!</h2>
<p>
<i class='fas fa-thermometer-half' style='color:#ca3517;'></i>
<span class='dht-labels'>Temperature</span>
<span>%.2f</span>
<sup class='units'>°C</sup>
</p>
<p>
<i class='fas fa-tint' style='color:#00add6;'></i>
<span class='dht-labels'>Humidity</span>
<span>%.2f</span>
<sup class='units'>%</sup>
</p>
</body>
</html>
)";
readDHTTemperature();
readDHTHumidity();
server.send(200, "text/html", response);
}
void setup(void) {
Serial.begin(115200);
dht.begin();
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
delay(2);
}
float readDHTTemperature() {
// Sensor readings may also be up to 2 seconds
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
if (isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return -1;
}
else {
Serial.println(t);
return t;
}
}
float readDHTHumidity() {
// Sensor readings may also be up to 2 seconds
float h = dht.readHumidity();
if (isnan(h)) {
Serial.println("Failed to read from DHT sensor!");
return -1;
}
else {
Serial.println(h);
return h;
}
}