#include <WiFi.h>
#include <PubSubClient.h>
#include "DHTesp.h"
const int DHT_PIN = 1;
DHTesp dhtSensor;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server="test.mosquitto.org";
WiFiClient espclient;
String temp_str; //see last code block below use these to convert the float that you get back from DHT
char temera[50];
String hum_str; //see last code block below use these to convert the float that you get back from DHT
char hum[50];
//Preparing for mqtt receive
void callback(char* topic,byte* payload,unsigned int length1)
{
Serial.print("message arrived[");
Serial.print(topic);
Serial.println("]");
for(int i=0;i<length1;i++){
Serial.print(payload[i]);
if(payload[0]==49)
{digitalWrite(2,HIGH);
Serial.print("LED ON");}//ASCII VALUE OF '1' IS 49
else if(payload[0]==50)
{digitalWrite(2,LOW);
Serial.print("LED OFF");}//ASCII VALUE OF '2' IS 50
Serial.println();
}
}
PubSubClient client(mqtt_server,1883,callback,espclient);
void setup() {
pinMode(2,OUTPUT);
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Connect to WIFI
Serial.print("connecting to ");
Serial.print(ssid);
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println();
}
void reconnect(){
while(WiFi.status()!=WL_CONNECTED){
delay(500);
Serial.print(".");
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
delay(2000);
//float t=30;
//float h=60;
TempAndHumidity data = dhtSensor.getTempAndHumidity();
float t = String(data.temperature, 2);
float h = String(data.humidity, 1);
//float t = (analogRead(0) * 3.3/2048 * 100);
Serial.print("Temperature Value is :");
Serial.print(t);
Serial.println("°C");
delay(1000);
Serial.print("Humidity Value is :");
Serial.print(h);
Serial.println("%");
delay(1000);
//Preparing for mqtt send
temp_str = String(t); //converting temperature (the float variable above) to a string
temp_str.toCharArray(temera, temp_str.length() + 1); //packaging up the data to publish to mqtt whoa...
hum_str = String(h); //converting temperature (the float variable above) to a string
hum_str.toCharArray(hum, hum_str.length() + 1); //packaging up the data to publish to mqtt whoa...
// Connect to Node-RED
if(client.connect("ESP32test1")){
Serial.println("Connected to Node-RED");
//client.subscribe("Control");
client.publish("amiss",temera);
client.publish("ecolex",hum);
}
else{
Serial.print("failed,rc=");
Serial.println(client.state());
delay(500);
}
}