#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#define WIFI_SSID "Hùng"
#define WIFI_PASSWORD "10032001"
WebServer server(80);
const int DHT_PIN = 5; // Chân kết nối với cảm biến DHT11
DHT dht(DHT_PIN, DHT11);
const char* openWeatherAPIKey = "5bc4744d80fe70be7ae30c344cfe9500";
const char* city = "Hanoi";
const char* openWeatherServer = "http://api.openweathermap.org";
const char* openWeatherEndpoint = "/data/2.5/weather";
String openWeatherQuery;
float temperature;
float humidity;
float openWeatherTemp;
float openWeatherHumidity;
void sendHtml() {
String response = "<!DOCTYPE html><html><head><title>Weather Information</title></head><body>";
response += "<h1>Weather Information</h1>";
response += "<p>Local Temperature: " + String(temperature) + " ℃</p>";
response += "<p>Local Humidity: " + String(humidity) + " %</p>";
response += "<p>OpenWeather Temperature: " + String(openWeatherTemp + 33) + " ℃</p>";
response += "<p>OpenWeather Humidity: " + String(openWeatherHumidity + 86) + " %</p>";
response += "</body></html>";
server.send(200, "text/html", response);
}
void getWeatherData() {
openWeatherQuery = String(openWeatherEndpoint) + "?q=" + city + "&appid=" + openWeatherAPIKey;
HTTPClient http;
http.begin(openWeatherServer, 80, openWeatherQuery);
int httpResponseCode = http.GET();
if (httpResponseCode == 200) {
String payload = http.getString();
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
openWeatherTemp = doc["main"]["temp"];
openWeatherHumidity = doc["main"]["humidity"];
}
http.end();
}
void setup(void) {
Serial.begin(115200);
dht.begin();
pinMode(DHT_PIN, INPUT_PULLUP);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, sendHtml);
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
temperature = dht.readTemperature();
humidity = dht.readHumidity();
getWeatherData(); // Lấy dữ liệu thời tiết từ OpenWeather API
server.handleClient();
delay(2000); // Delay để giảm tải CPU
}