#include <LiquidCrystal_I2C.h>
#include <PubSubClient.h>
#include <WiFi.h>
#include "DHTesp.h"
#include <ArduinoJson.h>
#include <HTTPClient.h>
LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display
String serverName = "https://postman-echo.com/get";
#define DHT_PIN 15
#define LED_PIN 32
#define LED_PIN2 14
#define LED_PIN3 2
#define PIR_SENSOR 12
DHTesp dhtSensor;
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (200) // Increased buffer size to accommodate larger JSON string
char msg[MSG_BUFFER_SIZE];
int value = 0;
WiFiClient espClient;
PubSubClient client(espClient);
const char* mqtt_server = "broker.emqx.io";
void setup() {
// Config LED_PIN output
pinMode(LED_PIN, OUTPUT);
// Setup for serial communication
Serial.begin(9600);
// Initialize the LCD
lcd.init();
lcd.backlight();
lcd.setCursor(1, 0);
lcd.print("ESP32 collecting data ...");
Serial.println("ESP32 collecting sensors data");
// Setup for DHT sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(PIR_SENSOR, INPUT);
delay(1000);
Serial.print("Connecting to WiFi");
//setup for WiFi connection
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println("WiFi Connected!");
}
void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
int temp = data.temperature;
int humid = data.humidity;
int pir_value = digitalRead(PIR_SENSOR);
unsigned long now = millis();
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
Serial.print("Temp: ");
Serial.print(temp);
Serial.print(", Humid: ");
Serial.print(humid);
Serial.print("\n");
}
// Update the LCD display
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temp);
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humid);
// Control LED based on PIR sensor value
if (pir_value == 1) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String serverPath = serverName + "?temp=24.7&humid=30";
http.begin(serverPath.c_str()); // Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: "); Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println(payload);
}
else {
Serial.print("Error code: "); Serial.println(httpResponseCode);
}
http.end();
}
else {
Serial.println("WiFi Disconnected");
}
delay(500);
}