// Full support for DHT22 on ESP32 (e.g., convert from the voltage signal produced
// by the sensor to the actual temperature value)
#include "DHTesp.h"
// Allows the ESP32 to connect to WiFi, to interact with the built-in WiFi module
#include <WiFi.h>
// Allow the ESP32 to support and talk the MQTT protocol, this library is an MQTT
// client implementation. Through this, we have all the tools needed to perform
// an MQTT connection
#include <PubSubClient.h>
// Pinout configuration
#define DHT_PIN 15
// Topic and client-ID static definition
#define MQTT_TOPIC "topicName/led"
#define CLIENT_ID "tataboxxe-wokwi"
// Network config (connection parameters)
// This is an SSID which is present on the simulation. Basically, in the Wokwi server
// there will be this AP called "Wokwi-GUEST", which we can connect to during a simulation.
// This is very good, because we can use a different connection from the one we are
// using to access the online Wokwi platform, we don't need to use our AP, our hotspot
// connection to connect to the Internet and the MQTT broker in particular, because
// Wokwi gives us the possibility to connect to their own AP in the simulation. We can
// access the Internet with a different connection/NIC
const char* ssid = "Wokwi-GUEST";
const char* password = ""; // Open WiFi LAN
const char* mqttServer = "broker.emqx.io"; // MQTT broker address
const int mqttPort = 1883;
// Payload of MQTT PUB messages
char temp_value[10];
DHTesp dht;
WiFiClient espClient;
PubSubClient client(espClient); // MQTT client, the PubSubClient ctor needs the WiFiClient object
// Configure WiFi client and establish connection
void wificonnect() {
// Set the ESP32 WiFi to station mode. The ESP32 acts as a WiFi station and can
// connect to an AP
WiFi.mode(WIFI_STA);
// Start the connection process
WiFi.begin(ssid, password);
// Wait for the ESP32 board to be connected
while (WiFi.status() != WL_CONNECTED) {
// Give time to connect!
delay(500);
Serial.print(".");
}
Serial.print("\n");
}
void setup() {
// Serial port setup
Serial.begin(115200);
// DHT22 setup
dht.setup(DHT_PIN, DHTesp::DHT22);
// WiFi setup
wificonnect();
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
// MQTT client setup
// Configure the MQTT client object and allow the MQTT client to connect to the broker
client.setServer(mqttServer, mqttPort);
if (client.connect(CLIENT_ID)) {
Serial.println("MQTT connected");
}
}
void loop() {
TempAndHumidity data = dht.getTempAndHumidity();
// snprintf() writes formatted data to a string, we use it to write the temperature
// data onto a string, in a string format (conversion from float to string)
sprintf(temp_value, "%.1f", data.temperature);
// Send PUB message with the latest temperature reading/sample/value
int a=0;
for(int i=0;temp_value[i]!='.';i++){
int b=(int)temp_value[i]-48;
a=a*10;a=a+b;
}
if(a>20){
client.publish(MQTT_TOPIC, temp_value);
}
//int aab=(int)temp_value;
//Serial.println("%d",aab);
delay(5000);
}