#include <PubSubClient.h>
#include <WiFi.h>
#include "DHTesp.h"
#include <NTPClient.h>
#include <WiFiUdp.h>
const int DHTPin = 15;
#define LED_BUILTIN 12
WiFiClient espClient;
PubSubClient mqttClient(espClient);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
DHTesp dhtSensor;
char tempArr[6];
bool isScheduledON = false;
unsigned long scheduledOnTime;
void setup() {
Serial.begin(115200);
dhtSensor.setup(DHTPin, DHTesp::DHT22);
setupWiFi();
setupMqtt();
timeClient.begin();
timeClient.setTimeOffset(5.5 * 3600);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
}
void loop() {
if (!mqttClient.connected()) {
Serial.println("Reconnecting to MQTT Broker");
connectTOBroker();
}
mqttClient.loop();
updateTemp();
Serial.println(tempArr);
mqttClient.publish("ENTC-TEMP_NI", tempArr);
checkSchedule();
delay(1000);
}
void setupWiFi() {
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Wifi Connected");
Serial.print("IP Adderss: ");
Serial.println(WiFi.localIP());
}
void setupMqtt() {
mqttClient.setServer("test.mosquitto.org", 1883);
mqttClient.setCallback(recieveCallback);
}
void connectTOBroker() {
while (!mqttClient.connected()) {
Serial.print("Attempting MQTT connection...");
if (mqttClient.connect("ESP32Client-sdfsjdfsdfsdf")) {
Serial.println("MQTT Connected");
mqttClient.subscribe("ENTC-ON-OFF_NI");
mqttClient.subscribe("ENTC-ADMIN-SCH-ON_NI");
} else {
Serial.print("Failed To connect to MQTT Broker");
Serial.print(mqttClient.state());
delay(5000);
}
}
}
void updateTemp() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
String(data.temperature, 2).toCharArray(tempArr, 6);
}
void recieveCallback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char payloadCharAr[length];
Serial.print("Message Recieved: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
payloadCharAr[i] = (char)payload[i];
}
Serial.println();
if (strcmp(topic, "ENTC-ON-OFF_NI") == 0) {
if (payloadCharAr[0] == '1') {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
} else if (strcmp(topic, "ENTC-ADMIN-SCH-ON_NI") == 0) {
if (payloadCharAr[0] == 'N') {
isScheduledON = false;
} else {
isScheduledON = true;
scheduledOnTime = atol(payloadCharAr);
}
}
}
unsigned long getTime() {
timeClient.update();
return timeClient.getEpochTime();
}
void checkSchedule() {
if (isScheduledON) {
unsigned long currentTime = getTime();
if (currentTime > scheduledOnTime) {
isScheduledON = false;
mqttClient.publish("ENTC-ADMIN-SCH-ESP-ON_NI", "0");
mqttClient.publish("ENTC-ADMIN-MAIN-ON-OFF-ESP_NI", "1");
Serial.println("Scheduled ON");
digitalWrite(LED_BUILTIN,HIGH);
}
}
}
// The code is pretty simple. We are using the DHTesp library to read the temperature and humidity from the DHT22 sensor. We are using the PubSubClient library to connect to the MQTT broker.
// The setup function is used to initialize the DHT sensor, connect to the WiFi network, and connect to the MQTT broker.
// The loop function is used to check if the MQTT client is connected to the broker. If not, it tries to reconnect. It then reads the temperature from the DHT sensor, publishes it to the MQTT broker, and waits for 1 second before repeating the process.
// The setupWiFi function is used to connect to the WiFi network. The setupMqtt function is used to connect to the MQTT broker. The connectToBroker function is used to reconnect to the MQTT broker if the connection is lost. The updateTemp function is used to read the temperature from the DHT sensor and store it in the tempArr array. The recieveCallback function is used to print the message received from the MQTT broker.
// Step 4: Upload the Code to the ESP32
// Now that we have written the code, we can upload it to the ESP32. To do this, follow these steps:
// Connect the ESP32 to your computer using a USB cable. Open the Arduino IDE. Go to Tools > Board and select the ESP32 Dev Module. Go to Tools > Port and select the port to which the ESP32 is connected. Click the Upload button to upload the code to the ESP32.
// Once the code is uploaded, you should see the temperature readings being published to the MQTT broker.
// Step 5: Test the MQTT Client
// To test the MQTT client, you can use an MQTT client like MQTT Explorer or MQTT.fx.
// Open the MQTT client and connect to the MQTT broker. Subscribe to the topic "ENTC-TEMP_NI". You should see the temperature readings being published to the topic.
// That's it! You have successfully created an MQTT client using an ESP32 and a DHT22 sensor.
// If you have any questions, feel free to ask in the comments section below.
// Comments
// Sanket on September 14, 2021:
// Hi,
// I am trying to run the code on ESP32 but I am getting the following error:
// Arduino: 1.8.15 (Windows 10), Board: "ESP32 Dev Module, Disabled, Default