/**
ESP32 + DHT22 and MQTT Example for Wokwi
https://wokwi.com/projects/341043726457504339
*/
#include <WiFi.h>
#include "DHTesp.h"
#include "PubSubClient.h"
#define LED 13
#define DHT_PIN 15
/**const int DHT_PIN = 15;*/
String T = "";
String H = "";
String pstring = "";
DHTesp dhtSensor;
WiFiClient espClient;
PubSubClient client(espClient);
// MQTT Broker
const char *mqtt_broker = "broker.mqttdashboard.com";
const char *topic_in = "tonitestin";
const char *topic_out = "tonitestout";
const char *mqtt_username = "";
const char *mqtt_password = "";
const int mqtt_port = 1883;
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(9600);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
//WiFi connection
Serial.print("Connecting to WiFi");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
//MQTT Broker connection
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public " + String(mqtt_broker) + " connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic_out, "Hello World, I'm ESP32");
client.subscribe(topic_in);
}
void callback(char *topic_in, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic_in);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(LED, HIGH);
} else {
digitalWrite(LED, LOW);
}
}
void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
T = "Temp: " + String(data.temperature, 2) + "°C";
H = "Humidity: " + String(data.humidity, 1) + "%";
pstring = T + ", " + H;
/**Serial.println(T);
Serial.println(H);
Serial.println("---");
*/
delay(1000);
int len = pstring.length();
char p [len];
pstring.toCharArray(p, len);
Serial.println("Message Out: " + pstring);
Serial.println("---");
client.publish(topic_out, p);
client.loop();
}