#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <uri/UriBraces.h>
#include "DHTesp.h"
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
const int DHT_PIN = 15;
float Temp;
float Humidity;
DHTesp dhtSensor;
WebServer server(80);
void sendHtml() {
String response = R"(
<!DOCTYPE html>
<html>
<head>
<title>ESP32 Web Server Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<style>
html { font-family: sans-serif;}
h1 { margin-bottom: 1.2em;
text-align: center; }
span {
margin: 0;
font-size: 30px;
text-align: center; }
div {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: auto auto;
grid-auto-flow: column;
grid-gap: 1em;
text-align: center; }
p {
border: none;
color: #fff;
padding: 0.5em 1em;
font-size: 2em;
text-decoration: none;
}
.temp { background-color: red; }
.humi { background-color: deepskyblue; }
</style>
</head>
<body>
<h1>ESP32 Web Server</h1>
<div>
<span>Nhiệt độ</span>
<p class="temp"> <span>)" + String(Temp, 1) + R"(</span> °C</p>
<span>Độ ẩm</span>
<p class="humi"> <span>)" + String(Humidity, 1) + R"(</span> %</p>
</div>
<form action="/convert" method="post">
<input type="submit" value="Chuyển sang độ F">
</form>
</body>
</html>
)";
server.send(200, "text/html", response);
}
void convertToF() {
Temp = Temp * 9/5 + 32;
}
void setup(void) {
Serial.begin(115200);
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());
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
server.on("/convert", HTTP_POST, [](){
convertToF();
sendHtml();
});
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Temp = data.temperature;
Humidity = data.humidity;
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
server.handleClient();
delay(2);
}