#include <WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ArduinoJson.h>
#include "DHTesp.h"
const char* ssid = "Wokwi-GUEST"; //declares a character array pointer ssid that points to a string literal "Wokwi-GUEST".
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
const char* stopic = "luuvachiase/led";
const char* ptopic = "luuvachiase/temp";
//const int oneWireBus = 4; // dùng pin GPIO4
const int DHT_PIN = 15; // DHT22
char result_temp[10]; // Buffer big enough for 7-character float
char result_hum[10]; // Buffer big enough for 7-character float
WiFiClient espClient; //This object represents a TCP/IP client connection to a Wi-Fi network.
PubSubClient client(espClient); // This object uses the espClient object as its underlying TCP/IP connection to connect to a MQTT broker
unsigned long lastMsg = 0;
DHTesp dhtSensor; // Use DHTesp class and use its methods to initialize the sensor
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) { //The string is terminated by a null character ('\0')
//is also the case for a const char* pointer in C.
Serial.println("connected");
// Once connected, publish an announcement...
client.publish(ptopic, "hello world");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void publish_temp()
{
TempAndHumidity data_temp = dhtSensor.getTempAndHumidity(); // the getTemperature() and getHumidity() methods
//to read the temperature and humidity data, respectively
dtostrf(data_temp.temperature, 6, 2, result_temp); // converts a floating-point number to a string,
//and stores the result in a character array.
dtostrf(data_temp.humidity, 6, 2, result_hum); // to a string with a width of 6 characters, including 2 digits to the right of the decimal point,
DynamicJsonDocument json(100); //create a dynamic, in-memory representation of a JSON document.
//This means that the size of the document is not fixed at compile time, and can be adjusted at runtime as needed.
json["temp"] = result_temp;
json["humi"] = result_hum;
String jsonString;
serializeJson(json, jsonString); // that allows you to serialize a JSON data structure into a string.
const char* payload = jsonString.c_str();
Serial.print("Publishing: ");
Serial.println(payload);
client.publish(ptopic, payload);
Serial.print("Done!");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(12, OUTPUT); // Initialize the BUILTIN_LED pin as an output
pinMode(14, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(115200);
// Start the DHT22 sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22); // use the dhtSensor.setup() method to initialize the sensor and
// dhtSensor.begin() method is typically called in settup
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
publish_temp();
delay(3000);
}