// ********** WOKWI DHT ********************
// ********** CONNECTION PART ******************
// library
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
// config
const char* WIFI_SSID = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const char* ID = "30697930-e1df-11ef-8e00-e370a74757c3";
const char* token = "Y0L4wvRy6kwORi0GJ7kT";
const char* password = "";
const char* thingsboard_server = "demo.thingsboard.io";
const int port = 1883;
// Network client
WiFiClient espClient;
PubSubClient client(espClient);
// define connection function
void chkConnection();
void InitWiFi();
bool reconnect();
void connectToMQTTBroker();
// ************** HARDWARE PART ****************
#include <DHT.h>
// pin
#define typeDHT DHT22
#define pinDHT 15
DHT dht(pinDHT, typeDHT);
// define hardware function
void sensorDHT();
// ******************** MAIN ********************
void setup() {
Serial.begin(9600);
InitWiFi();
client.setServer(thingsboard_server, port);
setHardware();
}
void loop() {
chkConnection();
// Call Function
sensorDHT();
client.loop();
delay(1000);
}
// ******************** Function ********************
void setHardware(){
dht.begin();
}
void chkConnection(){
// wifi
if (!reconnect()) {
return;
}
// mqtt
if (!client.connected()) {
connectToMQTTBroker();
}
}
void InitWiFi() {
Serial.println("📶Connecting to AP ...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(F("✅Connected to AP Success"));
}
bool reconnect() {
const wl_status_t status = WiFi.status();
if (status == WL_CONNECTED) {
return true;
}
InitWiFi();
return true;
}
void connectToMQTTBroker() {
while(!client.connected()) {
Serial.println("📶Connecting to ThingsBoard ...");
if(client.connect(ID, token, password)) {
Serial.println("✅Connected to ThingsBoard Success");
} else {
Serial.println("FAILED, retrying in 5 seconds");
delay(5000);
}
}
}
void sensorDHT() {
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
float hif = dht.computeHeatIndex(f, h);
float hic = dht.computeHeatIndex(t, h, false);
StaticJsonDocument<256> doc;
doc["Humidity"] = h;
doc["TemperatureC"] = t;
doc["TemperatureF"] = f;
doc["HeatIndexC"] = hic;
doc["HeatIndexF"] = hif;
String payload;
serializeJson(doc, payload);
client.publish("v1/devices/me/telemetry", payload.c_str());
client.publish("v1/devices/me/attributes", payload.c_str());
//Serial.println("Sending data...");
//Serial.println(payload);
}
Air quality station