#include "DHTesp.h"
#include <WiFi.h>
#include <PubSubClient.h>
// Defining variables
WiFiClient espClient;
PubSubClient client(espClient);
char Humidity[10];
char Temp[10];
DHTesp dhtSensor;
//Setip ESP32 WIFI
void setup() {
WiFi.mode(WIFI_STA);
WiFi.begin("Wokwi-GUEST", "");
client.setServer("broker.emqx.io", 1883);
Serial.begin(9600);
dhtSensor.setup(15, DHTesp::DHT22); //setup DHT sensor
}
void loop() { //connection recheck if connection goes down
if (!client.connected()) {
client.connect("clientId123");
Serial.println("ESP32 is Connected with MQTT!");
}
client.loop();
// Get the temp and humidity
TempAndHumidity data = dhtSensor.getTempAndHumidity();
sprintf(Humidity, "%.2f", data.humidity);
sprintf(Temp, "%.2fC", data.temperature);
//Print data
Serial.println("Humidity:");
Serial.println(Humidity);
Serial.println("Temperature:");
Serial.println(Temp);
//publish data
client.publish("python/iot", Humidity);
client.publish("python/iot", Temp);
delay(1000);
}