#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include <ArduinoJson.h>
// Replace with your network/wifi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace with your MQTT broker IP address or hostname
const char* mqtt_server = "broker.mqttdashboard.com";
const char* mqttUser = "";
const char* mqttPassword = "";
// Replace with your MQTT topic
const char* telemetry_topic = "iot/telemetry1"; //publish sensor data
// Replace with your DHT sensor type and pin
#define DHTPIN 15
#define DHTTYPE DHT22
// instantiate the libraries we import
DHT dht(DHTPIN, DHTTYPE); //DHT instance
WiFiClient espClient; //Wifi network instance
PubSubClient client(espClient); //Mqtt instance
//METHODS
//setup wifi to be called in setup() function
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
//when disconnected to mqtt while running
void reconnect() {
while (!client.connected()) {
Serial.println("Connecting to MQTT broker...");
if (client.connect("ESP32Client")) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed to connect to MQTT broker, rc=");
Serial.print(client.state());
Serial.println(" retrying in 5 seconds");
delay(5000);
}
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
while (!client.connected()) {
Serial.println("Connecting to MQTT server...");
if (client.connect("ESP32Client", mqttUser, mqttPassword)) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
if(!client.connected()){
// attempt to reconnect
if(client.connect("ESP32Client", mqttUser, mqttPassword)) {
Serial.println("Reconnected to mqtt server");
//once reconnected, resubscribe to the topic.
client.subscribe(telemetry_topic);
}
else {
Serial.println("Failed to reconnect with state ");
Serial.print(client.state());
delay(2000);
}
}
//keeping the MQTT connection alive
client.loop();
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read data from DHT sensor");
return;
}
// Create JSON object
DynamicJsonDocument jsonDoc(256);
jsonDoc["temperature"] = temperature;
jsonDoc["humidity"] = humidity;
// Serialize JSON object
String jsonString;
serializeJson(jsonDoc, jsonString);
// Publish data to MQTT server
client.publish(telemetry_topic, jsonString.c_str()); // the second parameter expects a const char* data type. so convert it to string object.
// Print sensor data and JSON object
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\t");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("JSON: ");
Serial.println(jsonString);
// Wait 5 seconds before next reading
delay(5000);
}