#include <WiFi.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "DHT.h"
#include <ArduinoJson.h>
#include <PubSubClient.h>
#define DHTPIN 15 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
#define PIR 4
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 22, 4); // set the LCD address to 0x27 for a 22 chars and 4 line display
int BUILTIN_LED = 32; // choose the pin for the LED
int inputPin = 12; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0;
int humid, temp;
const char *ssid = "Wokwi-GUEST";
const char *password = "";
const char *mqtt_server = "broker.mqtt-dashboard.com";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (200) // Increase buffer size to handle larger JSON messages
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup()
{
// Setup for serial communication
Serial.begin(9600);
lcd.init(); // Initialize the LCD
lcd.backlight();
lcd.setCursor(1, 0);
lcd.print("ESP32 collecting data ...");
delay(1000);
dht.begin();
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop()
{
readData();
if (!client.connected())
{
reconnect();
}
client.loop();
unsigned long now = millis();
if (now - lastMsg > 2000)
{
lastMsg = now;
++value;
// Create JSON document
DynamicJsonDocument doc(200);
doc["message"] = "hello world";
doc["humidity"] = humid;
doc["temperature"] = temp;
// Serialize JSON document to a char array
serializeJson(doc, msg);
Serial.print("Publish message: ");
Serial.println(msg);
// Publish the JSON message
client.publish("outTopic", msg);
}
}
void readData()
{
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
humid = dht.readHumidity();
temp = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(humid) || isnan(temp))
{
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(temp, humid, false);
// Print to Screen
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Humidity: ");
lcd.print(humid);
lcd.println("%");
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(temp);
lcd.println("C");
}
void setup_wifi()
{
delay(10);
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 callback(char *topic, byte *payload, unsigned int length)
{
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == '1')
{
digitalWrite(BUILTIN_LED, LOW);
delay(1000);
}
else
{
digitalWrite(BUILTIN_LED, HIGH);
delay(1000);
}
}
void reconnect()
{
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
client.publish("outTopic", "hello everyone");
client.subscribe("inTopic");
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}