#include "DHTesp.h" // Library for interfacing with DHT sensor
#include <WiFi.h> // Library for WiFi functions
#include <HTTPClient.h> // Library for HTTP client (not used in this code but included)
#include <ArduinoJson.h> // Library for JSON (not used in this code but included)
#include <PubSubClient.h> // Library for MQTT client
// WiFi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT Server Parameters
const char *channel = "DHT-MQTT";
const char clientID[] = "micropython-weather-demo"; // Client ID for MQTT broker
const char host[] = "broker.mqttdashboard.com"; // MQTT broker address
String payload;
const int DHT_PIN = 15; // Pin connected to DHT sensor
float temperature; // Variable to store temperature
float humidity; // Variable to store humidity
String tempStr, humStr; // Strings to hold formatted temperature and humidity data
DHTesp capteur; // DHT sensor object
WiFiClient Clientwifi; // WiFi client object
PubSubClient clientmqtt(host, 1883, Clientwifi); // MQTT client object
void setup() {
Serial.begin(115200); // Initialize serial communication at 115200 baud
Serial.println("Hello, ESP32!"); // Print a welcome message
capteur.setup(DHT_PIN, DHTesp::DHT22); // Setup the DHT sensor on specified pin
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { // Wait until connected to WiFi
Serial.print(".");
delay(1000);
}
Serial.println("Wifi Connected"); // Print a message when connected
}
void loop() {
// Check if MQTT client is connected
if (!clientmqtt.connected()) {
Serial.println("MQTT NOT connected"); // Print message if not connected
delay(1000);
if(clientmqtt.connect(clientID)) { // Try to connect to the MQTT broker
Serial.println("MQTT connected"); // Print message if connected
}
}
else { // If already connected to MQTT broker
Serial.println("MQTT connected"); // Print message
delay(1000);
// Read temperature and humidity from DHT sensor
temperature = capteur.getTemperature();
humidity = capteur.getHumidity();
Serial.print("Temperature:"); Serial.println(temperature); // Print temperature
Serial.print("Humidity:"); Serial.println(humidity); // Print humidity
// Format temperature and humidity as strings
tempStr = "Temperature:" + String(temperature);
humStr = "Humidity:" + String(humidity);
// Combine temperature and humidity strings into payload
payload = tempStr + "," + humStr;
// Publish the payload to the "weather" topic
clientmqtt.publish("weather", payload.c_str());
Serial.println("MQTT DATA sent"); // Print message indicating data was sent
}
clientmqtt.loop(); // Process MQTT messages
Serial.println();
delay(1000); // Wait for 1 second before repeating loop
}