#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
// Pin definitions
#define DHT_PIN 16
#define BUZZER 12
// Initialize necessary objects
WiFiClient espClient;
PubSubClient mqttClient(espClient);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
// Character array to hold temperature data
char temp[6];
// Initialize DHT sensor object
DHTesp dhtSensor;
// Variables for scheduled ON/OFF control
bool isScheduledON = false;
unsigned long scheduledOnTime;
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(temp);
mqttClient.publish("Environment-Temperature", temp);
// Check if it's time to turn on the buzzer based on schedule
checkSchedule();
// Delay to prevent flooding the MQTT broker
delay(1000);
}
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);
}
// Setup MQTT connection parameters
void setupMqtt() {
// Set MQTT server and callback function
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("] ");
// Convert payload to char array
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, "MediBox-ON-OFF") == 0) {
buzzerOn(payloadCharAr[0] == '1');
} else if (strcmp(topic, "MediBox-ON") == 0) {
if (payloadCharAr[0] == 'N') {
isScheduledON = false;
} else {
isScheduledON = true;
scheduledOnTime = atol(payloadCharAr);
}
}
}
// Connect to MQTT broker
void connectToBroker() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect("ESP32-12345645454")) {
Serial.println("connected");
mqttClient.subscribe("MediBox-ON-OFF");
mqttClient.subscribe("MediBox-ON");
} else {
Serial.println("Connection failed");
Serial.println(mqttClient.state());
delay(5000);
}
}
}
// Function to control buzzer
void buzzerOn(bool on) {
if (on) {
tone(BUZZER, 256);
} else {
noTone(BUZZER);
}
}
// Read temperature from DHT sensor
void updateTemperature() {
// Get temperature data from DHT sensor
TempAndHumidity data = dhtSensor.getTempAndHumidity();
// Convert temperature to string and store in char array
String(data.temperature, 2).toCharArray(temp, 6);
}
// Setup WiFi connection
void setupWifi() {
Serial.println();
Serial.print("Connecting to WiFi network...");
// Connect to WiFi network
WiFi.begin("Wokwi-GUEST", "");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(5000);
Serial.print(".");
}
// Connection successful
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
// Get current time from NTP server
unsigned long getTime() {
// Update time from NTP server
timeClient.update();
// Return current epoch time
return timeClient.getEpochTime();
}
// Check if it's time to execute scheduled actions
void checkSchedule() {
if (isScheduledON) {
unsigned long currentTime = getTime();
// Check if current time is past scheduled ON time
if (currentTime > scheduledOnTime) {
// Turn on buzzer
buzzerOn(true);
// Update status
isScheduledON = false;
// Publish status to MQTT
mqttClient.publish("MediBox-ON-OFF-ESP", "1");
mqttClient.publish("MediBox-ESP-ON", "0");
Serial.println("Scheduled ON");
}
}
}