#include <WiFi.h>
#include <PubSubClient.h>
#include <DHTesp.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define TOKEN "eeP54TgkQ0K1EcB7Y4B6"
#define MQTT_SERVER "thingsboard.cloud"
#define MQTT_PORT 1883
const int DHT_PIN = 15;
DHTesp dht;
WiFiClient espClient;
PubSubClient client(espClient);
// -------------------- CONNECT WIFI --------------------
void setupWifi() {
Serial.print("Connecting to WiFi");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" OK");
}
// -------------------- RECONNECT MQTT --------------------
void reconnectMQTT() {
while (!client.connected()) {
Serial.print("Connecting to ThingsBoard MQTT...");
if (client.connect("ESP32_DHT22", TOKEN, "")) {
Serial.println("connected!");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
setupWifi();
client.setServer(MQTT_SERVER, MQTT_PORT);
dht.setup(DHT_PIN, DHTesp::DHT22);
}
void loop() {
if (!client.connected()) {
reconnectMQTT();
}
client.loop();
TempAndHumidity data = dht.getTempAndHumidity();
float temp = data.temperature;
float hum = data.humidity;
Serial.print("Temp: ");
Serial.print(temp);
Serial.print(" °C | Hum: ");
Serial.println(hum);
// Build JSON payload
String payload = "{";
payload += "\"temperature\":";
payload += temp;
payload += ",\"humidity\":";
payload += hum;
payload += "}";
client.publish("v1/devices/me/telemetry", payload.c_str());
delay(3000);
}