#include <PubSubClient.h>
#include <WiFi.h>
#include "DHTesp.h"
#define LED_BUILTIN 2
const int DHT_PIN = 15;
WiFiClient espClient;
PubSubClient mqttClient(espClient); //create an instance of espClient
DHTesp dhtSensor;
char tempAr[6]; //the maximum val we want is about 100.00
void setup() {
Serial.begin(115200);
setupWifi();
setupMqtt();
dhtSensor.setup(DHT_PIN, DHTesp :: DHT22); //initialize the tempsensor
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
}
void loop() {
//cjecks whether it is connected to the mqtt client
if(!mqttClient.connected()){
connectToBroker();
}
mqttClient.loop();
updateTemperature();
Serial.println(tempAr);
mqttClient.publish("ENTC-TEMP", tempAr); //only accepts charater arrays
delay(1000);
}
void setupWifi(){
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void setupMqtt(){
mqttClient.setServer("test.mosquitto.org",1883);
mqttClient.setCallback(receiveCallback);
}
void connectToBroker(){
while(!mqttClient.connected()){
Serial.println("Attempting MQTT connection.....");
//if we don't want authentication, we can have any random name
if(mqttClient.connect("ESP32-665959999")){
Serial.println("Connected");
mqttClient.subscribe("ENTC-ON-OFF");
}else{
Serial.print("Failed");
Serial.print(mqttClient.state());
delay(5000); //better to have a delay
}
}
}
void updateTemperature(){
TempAndHumidity data = dhtSensor.getTempAndHumidity();
//convert to a string with 2 decimal places
String(data.temperature,2).toCharArray(tempAr,6);// the place where we need to store and the length of the array
}
void receiveCallback(char* topic, byte* payload, unsigned int length){
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("]");
char payloadCharAr[length]; //varibale to store incoming data
for (int i=0; i <length;i++){
Serial.print((char)payload[i]);
payloadCharAr[i] = (char)payload[i];
}
Serial.println();
//comapre the topic with the given one
//if the given 2 matches, the val will be zero
if(strcmp(topic, "ENTC-ON-OFF") == 0){
if(payloadCharAr[0] == '1'){
digitalWrite(LED_BUILTIN , HIGH);
}else{
digitalWrite(LED_BUILTIN , LOW);
}
}
}