In this fifth part of our IoT project series, we explore environmental monitoring with ESP32-based temperature and humidity sensing. This project demonstrates real-time data acquisition, threshold-based alerting, and advanced dashboard visualization with logging capabilities.
Project OverviewThis ESP32 project implements a comprehensive environmental monitoring system with MQTT communication and intelligent alerting. It features a DHT22 sensor for precise measurements, configurable thresholds, and real-time alerts with buzzer notifications. The Wokwi simulation shows a clean sensor setup:
- DHT22 Sensor: Connected to GPIO 15 for temperature and humidity readings
- Buzzer: Connected to GPIO 4 for audio alerts when thresholds are exceeded
- Power: 5V supply for DHT22 sensor, common ground configuration
- Communication: MQTT messaging with JSON threshold configuration
The firmware uses an event-driven approach with four core components. Connection Management handles WiFi with auto-reconnect, MQTT with authentication, and subscription management. Sensor Processing provides DHT22 data acquisition with error handling, dual temperature units (Celsius/Fahrenheit), and 1-second update intervals. Threshold Monitoring implements JSON-based configuration, real-time comparison, and alert generation. Alert System features buzzer activation with timed duration, MQTT alert publishing, and intelligent alert prevention.
MQTT Communication Protocol
The system uses structured MQTT topics for comprehensive monitoring:
arduino/Weather
- Sensor data publishingarduino/Weather_threshold
- JSON threshold configurationarduino/weather_alerts
- Alert notificationsmqtt/request
- System control commandsmqtt/response
- Device status reports
Message Formats:
Sensor Data: "Temperature: 25.4°C, Temperature: 77.7°F, Humidity: 65.2%"
Threshold Config: {"temp": 30.0, "hum": 70.0}
Status Response: "Board : ESP32 Status : Connected"
Alert Message: "HighTemp:32.1 °C > 30.0 °C"
Key Firmware Features
JSON Threshold Processing:
void handle_threshold(String payload) {
StaticJsonDocument<128> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
if (doc["temp"].is<float>()) temp_threshold = doc["temp"];
if (doc["hum"].is<float>()) hum_threshold = doc["hum"];
}
}
Intelligent Alert System:
void check_thresholds(float temp, float hum) {
bool shouldAlert = false;
String alertMessage = "";
if (temp > temp_threshold) {
alertMessage += "HighTemp:" + String(temp, 1) + " °C > " + String(temp_threshold, 1) + " °C";
shouldAlert = true;
}
if (shouldAlert && buzzerStartTime == 0) {
activate_buzzer();
client.publish(ALERT_TOPIC, alertMessage.c_str());
}
}
Buzzer Control with Duration:
void activate_buzzer() {
ledcSetup(0, 1000, 8); // Channel 0, 1kHz, 8-bit resolution
ledcAttachPin(BUZZER_PIN, 0);
ledcWriteTone(0, 1000); // 1kHz tone
buzzerStartTime = millis();
}
void check_buzzer() {
if (buzzerStartTime != 0 && (millis() - buzzerStartTime) > buzzerDuration) {
ledcWriteTone(0, 0); // Stop tone
buzzerStartTime = 0;
}
}
PyQt5 Dashboard Integration
The dashboard interface provides comprehensive monitoring through four main sections:
- MQTT Status Panel - Connection monitoring with LED indicators
- Sensor Data Display - Real-time temperature (°C/°F) and humidity values
- Threshold Configuration - Adjustable limits with instant application
- Logging System - Separate action and alert logs with timestamps
Signal-Based Architecture
The Python implementation uses PyQt5's signal-slot mechanism for thread-safe updates:
class Tem_hum_Sensor(QObject):
# Signal definitions for thread-safe UI updates
update_tempC = pyqtSignal(str)
update_tempF = pyqtSignal(str)
update_hum = pyqtSignal(str)
update_board_status = pyqtSignal(str, str, str)
log_action = pyqtSignal(str)
log_alert = pyqtSignal(str)
update_threshold_values = pyqtSignal(float, float)
Thread-Safe Data Updates:
def _update_tempC(self, value):
self.ui.tempC_val_label.setText(f"{value} °C")
def _log_alert(self, message):
timestamp = datetime.now().strftime("%H:%M:%S")
self.ui.alert_log.append(f'<span style="color:white;">[{timestamp}] {message}</span>')
MQTT Message Handling
Weather Data Processing:
def handle_weather_message(self, topic, payload):
if "Temperature:" in payload and "Humidity:" in payload:
tempC_part = payload.split("Temperature: ")[1].split(",")[0]
tempC = tempC_part.replace("°C", "").strip()
self.update_tempC.emit(tempC)
tempF_part = payload.split("Temperature: ")[2].split(",")[0]
tempF = tempF_part.replace("°F", "").strip()
self.update_tempF.emit(tempF)
hum_part = payload.split("Humidity: ")[1].replace("%", "").strip()
self.update_hum.emit(hum_part)
Status Monitoring:
def handle_status_message2(self, topic, payload):
if "Board :" in payload and "Status :" in payload:
board_part, status_part = payload.split("Status :")
board_name = board_part.replace("Board :", "").strip()
status = status_part.strip().lower()
if status == "connected":
self.update_board_status.emit(board_name, "Connected", "green")
self.update_led_status.emit("green")
Control Flow Analysis
Dashboard to Hardware Flow:
- Threshold Configuration: User adjusts temperature/humidity spinboxes in dashboard
- JSON Publishing: Threshold values sent as JSON to
arduino/Weather_threshold
topic - ESP32 Processing: Message received, parsed, and thresholds updated
- Confirmation: Action logged in dashboard for user feedback
- Monitoring Active: New thresholds immediately applied to incoming sensor data
Hardware to Dashboard Flow:
- Sensor Reading: DHT22 provides temperature and humidity measurements
- Data Publishing: Formatted sensor data sent to
arduino/Weather
topic - Dashboard Update: Real-time display updates with latest values
- Threshold Check: ESP32 compares values against configured limits
- Alert Generation: Exceeded thresholds trigger buzzer and alert messages
Advanced Features
JSON Threshold Management:
def update_thresholds(self):
temp_val = self.ui.temp_spinbox.value()
hum_val = self.ui.humidity_spinbox.value()
thresholds = {"temp": temp_val, "hum": hum_val}
self.log_action.emit(f"Thresholds sent: {thresholds}")
payload = json.dumps(thresholds)
self.mqtt_client.publish(MQTT_TOPIC_WATHER_THRESHOLD, payload)
Dual Logging System:
def _log_action(self, message):
timestamp = datetime.now().strftime("%H:%M:%S")
self.ui.action_log.append(f"[{timestamp}] {message}")
def _log_alert(self, message):
timestamp = datetime.now().strftime("%H:%M:%S")
self.ui.alert_log.append(f'<span style="color:white;">[{timestamp}] {message}</span>')
System Deactivation with Cleanup:
def deactivate(self):
self.mqtt_client.publish(MQTT_TOPIC_MQTT_Rq, "TurnOFF")
self.mqtt_client.unsubscribe_from_topic(MQTT_TOPIC_WATHER)
self.mqtt_client.unsubscribe_from_topic(MQTT_TOPIC_WATHER_ALERTS)
self.update_tempC.emit("--")
self.update_tempF.emit("--")
self.update_hum.emit("--")
self.ui.action_log.clear()
self.ui.alert_log.clear()
ConclusionThis ESP32 temperature and humidity monitoring project demonstrates advanced IoT sensor integration with intelligent alerting and comprehensive dashboard visualization. The system provides real-time environmental monitoring with configurable thresholds, audio alerts, and detailed logging capabilities.
In the next part of this series, IoT Projects Part 6: Water Level Control System, we'll explore liquid level sensing and pump control automation with safety interlocks and remote monitoring capabilities.
That's all!If you have any questions or suggestions, don’t hesitate to leave a comment below.
Comments