#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#include <ArduinoJson.h>
// WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT
const char* mqtt_server = "mqtt.eclipseprojects.io";
const char* mqtt_topic = "esp32/temperature";
WiFiClient espClient;
PubSubClient client(espClient);
// DHT22
#define DHTPIN 15
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// Analog pin (simulate thermistor)
#define THERM_PIN 34
void setup_wifi() {
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password, 6); // Wokwi uses channel 6
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" connected!");
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connecting to MQTT...");
if (client.connect("ESP32Client")) {
Serial.println(" connected");
} else {
Serial.print(" failed, rc=");
Serial.println(client.state());
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
}
float convertAnalogToCelsius(int analogValue) {
// Simulate 0–100°C from 0–4095
return (analogValue / 4095.0) * 100.0;
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
float dhtTemp = dht.readTemperature();
int analogValue = analogRead(THERM_PIN);
float thermTemp = convertAnalogToCelsius(analogValue);
if (isnan(dhtTemp)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Format JSON
StaticJsonDocument<128> doc;
doc["dht"] = dhtTemp;
doc["therm"] = thermTemp;
char jsonBuffer[128];
serializeJson(doc, jsonBuffer);
client.publish(mqtt_topic, jsonBuffer);
Serial.println(jsonBuffer);
delay(5000); // Every 5 seconds
}