// includes necessary libraries for MQTT communication
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
#define DHT_PIN 12
#define BUZZER 16
//The code initializes necessary objects including
//WiFi, MQTT client, NTP client, and DHT sensor.
WiFiClient espClient;
PubSubClient mqttClient(espClient);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
// Character array to hold temperature data
char tempAr[6];
// Initialize DHT sensor object
DHTesp dhtSensor;
// Variables for scheduled ON/OFF control
bool isScheduledON = false;
unsigned long scheduledOnTime;
/**
*It connects to the WiFi network and sets up the
* MQTT connection parameters, including the server and
*callback function for receiving messages.
*/
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Setup WiFi and MQTT connections
setupWifi();
setupMqtt();
// Setup DHT sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Initialize NTP client
timeClient.begin();
timeClient.setTimeOffset(5.5 * 3600);
// Setup buzzer pin
pinMode(BUZZER, OUTPUT);
digitalWrite(BUZZER, LOW);
}
/**The main loop handles MQTT connection,
*temperature reading from the DHT sensor,
* publishing temperature data to MQTT,
*and checking for scheduled actions.
*/
void loop() {
// Reconnect to MQTT broker if not connected
if (!mqttClient.connected()) {
connectToBroker();
}
mqttClient.loop();
// Update temperature reading and publish to MQTT
updateTemperature();
Serial.println(tempAr);
mqttClient.publish("Ambient-Temperature", tempAr);
// Check if it's time to turn on the buzzer based on schedule
checkSchedule();
// Delay to prevent flooding the MQTT broker
delay(1000);
}
// Function to control buzzer
void buzzerOn(bool on) {
if (on) {
tone(BUZZER, 256);
} else {
noTone(BUZZER);
}
}
/**
*This function is responsible for setting up the MQTT connection
* parameters and defining the callback function to handle
*incoming MQTT messages
*/
void setupMqtt() {
mqttClient.setServer("test.mosquitto.org", 1883);
mqttClient.setCallback(receiveCallback);
}
// Callback function for receiving MQTT messages
void receiveCallback(char *topic, byte *payload, unsigned int length) {
// Print received message
Serial.print("Message has arrived [");
Serial.print(topic);
Serial.print("] ");
char payloadCharAr[length];
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
payloadCharAr[i] = (char)payload[i];
}
Serial.println();
// Check topic and act accordingly
if (strcmp(topic, "System-ON-OFF") == 0) {
buzzerOn(payloadCharAr[0] == '1');
} else if (strcmp(topic, "System-ON") == 0) {
if (payloadCharAr[0] == 'N') {
isScheduledON = false;
} else {
isScheduledON = true;
scheduledOnTime = atol(payloadCharAr);
}
}
}
/**
*This function repeatedly tries to connect the ESP32 device
* to the MQTT broker until successful, subscribing to relevant
*topics upon connection. If connection fails, it logs the error and
*retries after a delay.
*/
void connectToBroker() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect("ESP32-12345645454")) {
Serial.println("connected");
mqttClient.subscribe("System-ON-OFF");
mqttClient.subscribe("System-ON");
} else {
Serial.println("failed");
Serial.println(mqttClient.state());
delay(5000);
}
}
}
// Read temperature from DHT sensor
void updateTemperature() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
String(data.temperature, 2).toCharArray(tempAr, 6);
}
// Setup WiFi connection
void setupWifi() {
Serial.println();
Serial.print("Connecting to ");
Serial.println("Wokwi-GUEST");
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(5000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
// Get current time from NTP server
unsigned long getTime() {
timeClient.update();
return timeClient.getEpochTime();
}
// Check if it's time to execute scheduled actions
void checkSchedule() {
if (isScheduledON) {
unsigned long currentTime = getTime();
if (currentTime > scheduledOnTime) {
buzzerOn(true);
isScheduledON = false;
// Publish status to MQTT
mqttClient.publish("System-ON-OFF-ESP", "1");
mqttClient.publish("System-ESP-ON", "0");
Serial.println("Scheduled ON");
}
}
}
/**
*The code sets up an ESP32 device to connect to an MQTT broker
*for IoT communication.
*/