#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include <ArduinoJson.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.emqx.io";
const int mqtt_port = 1883;
const char* mqtt_topic = "nhietdoam";
const char* MQTT_ID = "esp32_client_1";
const int DHTPIN = 15;
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
dht.begin();
}
void setup_wifi() {
delay(10);
Serial.println("Kết nối với WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi đã kết nối thành công");
}
void reconnect() {
while (!client.connected()) {
Serial.print("Kết nối đến MQTT broker...");
if (client.connect(MQTT_ID)) {
Serial.println("Đã kết nối thành công với MQTT broker");
} else {
Serial.print("Lỗi kết nối, rc=");
Serial.print(client.state());
Serial.println(" Thử lại sau 5 giây");
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Đọc dữ liệu từ cảm biến DHT22
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Tạo thông điệp JSON
char message[50];
snprintf(message, 50, "{\"temperature\": %.2f, \"humidity\": %.2f}", temperature, humidity);
// Gửi thông điệp lên broker
client.publish(mqtt_topic, message);
Serial.print("Thông tin la: ");
Serial.println(message);
delay(10000);
}
// <!DOCTYPE html>
// <html>
// <head>
// <title>Thông tin Nhiệt độ và Độ ẩm</title>
// <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
// </head>
// <body>
// <h1>Thông tin Nhiệt độ và Độ ẩm</h1>
// <p>Nhiệt độ hiện tại: <span id="temperature">Đang tải...</span></p>
// <p>Độ ẩm hiện tại: <span id="humidity">Đang tải...</span></p>
// <p>Nhiệt độ trung bình (3 lần đo gần nhất): <span id="avgTemperature">Đang tính...</span></p>
// <p id="humidityWarning" style="color: red; display: none;">Độ ẩm cao!</p>
// <script>
// // Tạo client MQTT với WebSocket và tạo Client ID duy nhất
// var client = new Paho.MQTT.Client("broker.emqx.io", Number(8083), "clientId_" + new Date().getTime());
// client.onConnectionLost = onConnectionLost;
// client.onMessageArrived = onMessageArrived;
// // Kết nối với MQTT broker
// client.connect({
// onSuccess: onConnect,
// useSSL: false // Nếu muốn sử dụng SSL, hãy chuyển cổng thành 8084 và đặt useSSL thành true
// });
// // Mảng lưu trữ 3 lần đo nhiệt độ gần nhất
// let temperatureReadings = [];
// function onConnect() {
// console.log("Kết nối thành công với MQTT Broker");
// client.subscribe("nhietdoam");
// }
// function onConnectionLost(responseObject) {
// if (responseObject.errorCode !== 0) {
// console.log("Mất kết nối: " + responseObject.errorMessage);
// }
// }
// function onMessageArrived(message) {
// console.log("Nhận được dữ liệu: " + message.payloadString);
// try {
// // Chuyển đổi chuỗi JSON thành đối tượng
// const data = JSON.parse(message.payloadString);
// if (data.temperature !== undefined) {
// updateTemperature(parseFloat(data.temperature));
// }
// if (data.humidity !== undefined) {
// updateHumidity(parseFloat(data.humidity));
// }
// } catch (error) {
// console.log("Lỗi khi phân tích dữ liệu JSON:", error);
// }
// }
// function updateTemperature(temperature) {
// if (isNaN(temperature)) return;
// // Hiển thị nhiệt độ hiện tại
// document.getElementById('temperature').textContent = temperature + ' °C';
// // Thêm giá trị nhiệt độ vào mảng và giữ lại 3 lần đo gần nhất
// temperatureReadings.push(temperature);
// if (temperatureReadings.length > 3) {
// temperatureReadings.shift(); // Loại bỏ giá trị đầu tiên nếu có hơn 3 giá trị
// }
// // Tính nhiệt độ trung bình
// const avgTemperature = (temperatureReadings.reduce((a, b) => a + b, 0) / temperatureReadings.length).toFixed(2);
// document.getElementById('avgTemperature').textContent = avgTemperature + ' °C';
// }
// function updateHumidity(humidity) {
// if (isNaN(humidity)) return;
// // Hiển thị độ ẩm hiện tại
// document.getElementById('humidity').textContent = humidity + ' %';
// // Kiểm tra nếu độ ẩm > 85%, hiển thị cảnh báo
// if (humidity > 85) {
// document.getElementById('humidityWarning').style.display = 'block';
// } else {
// document.getElementById('humidityWarning').style.display = 'none';
// }
// }
// </script>
// </body>
// </html>
// https://www.guidgen.com/
// https://wokwi.com/projects/382736745923167233
// https://wokwi.com/projects/382703605521123329
// https://wokwi.com/projects/382719631821757441
// https://wokwi.com/makers/baothanngg