#include <WiFi.h>
#include <DHT.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>
// Đặt thông tin WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Đặt thông tin máy chủ web
const int serverPort = 80;
WiFiServer server(serverPort);
// Đặt thông tin cảm biến DHT
#define DHT_PIN 4
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);
// Đặt thông tin OpenWeather API
const char* openWeatherApiKey = "6643cb5824f7c8e5e5951a43c38098a9";
const char* city = "HaNoi"; // Tên thành phố
void setup() {
Serial.begin(115200);
delay(1000);
// Kết nối đến mạng Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Khởi tạo cảm biến DHT
dht.begin();
// Khởi tạo máy chủ web
server.begin();
}
void loop() {
// Đọc dữ liệu nhiệt độ và độ ẩm từ cảm biến DHT
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Gửi yêu cầu lấy thông tin thời tiết từ OpenWeather API
String weatherData = getWeatherData();
// Xây dựng trang web và hiển thị dữ liệu
String webPage = buildWebPage(temperature, humidity, weatherData);
// Xử lý yêu cầu từ trình duyệt web
WiFiClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.print(webPage);
break;
}
}
client.stop();
}
delay(30000); // Chờ 30 giây trước khi cập nhật dữ liệu
}
String getWeatherData() {
HTTPClient http;
String weatherUrl = "http://api.openweathermap.org/data/2.5/weather?q=" + String(city) + "&appid=" + String(openWeatherApiKey);
http.begin(weatherUrl);
int httpCode = http.GET();
String weatherData = "";
if (httpCode > 0) {
weatherData = http.getString();
}
http.end();
return weatherData;
}
String buildWebPage(float temperature, float humidity, String weatherData) {
String page = "<html><body>";
page += "<h1>Thông tin môi trường</h1>";
page += "<p>Nhiệt độ: " + String(temperature) + " ℃</p>"; // Hiển thị độ C
page += "<p>Độ ẩm: " + String(humidity) + " %</p>";
page += "<h1>Thông tin thời tiết</h1>";
page += "<p>" + parseWeatherData(weatherData) + "</p>";
page += "</body></html>";
return page;
}
String parseWeatherData(String jsonWeatherData) {
JSONVar data = JSON.parse(jsonWeatherData);
String description = data["weather"][0]["description"];
String temperatureK = data["main"]["temp"];
float temperatureC = temperatureK.toFloat() - 273.15; // Chuyển đổi từ độ K sang độ C
String weatherInfo = "Thời tiết hiện tại: " + description + "<br>";
weatherInfo += "Nhiệt độ: " + String(temperatureC) + " ℃<br>"; // Hiển thị độ C
return weatherInfo;
}