#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"
// WiFi & MQTT Settings
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.emqx.io";
// Topics
const char* publish_topic = "np/std1/sensor/DHT22";
const char* subscribe_topic = "sph2/room/LED";
// Pins
const int DHT_PIN = 15;
const int LED_PIN = 23;
WiFiClient espClient;
PubSubClient client(espClient);
DHTesp dhtSensor;
unsigned long lastMsg = 0;
// This function runs when a message arrives from the broker
void callback(char* topic, byte* payload, unsigned length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.println(message);
// Check the payload
if (string(topic) == "sph2/room/LED"){
if (message == "On") {
digitalWrite(LED_PIN, HIGH);
Serial.println("LED is ON");
} else if (message == "Off") {
digitalWrite(LED_PIN, LOW);
Serial.println("LED is OFF");
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
client.setServer(mqtt_server, 1883);
client.setCallback(callback); // Set the function to handle incoming messages
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("ESP32_Client_Room1")) {
Serial.println("connected");
// Subscribe to the LED topic after connecting
client.subscribe(subscribe_topic);
} else {
delay(5000);
}
}
}
void loop() {
if (!client.connected()) reconnect();
client.loop(); // Essential for receiving messages
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
TempAndHumidity data = dhtSensor.getTempAndHumidity();
if (!isnan(data.temperature)) {
String msg = "{\"temp\":" + String(data.temperature, 1) + "}";
client.publish(publish_topic, msg.c_str());
}
}
}