#include <LiquidCrystal_I2C.h>
#include "DHTesp.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <string.h>
String GET_METHOD = "https://postman-echo.com/get";
String POST_METHOD = "https://postman-echo.com/post";
#define LED_PIN 32
#define DHT_PIN 15
#define PIR_SENSOR 12
LiquidCrystal_I2C lcd(0x27, 20, 4); // set the LCD address to 0x27 for a 16 chars and 2 line display
DHTesp dhtSensor;
void setup() {
// Config LED_PIN output
pinMode(LED_PIN, OUTPUT);
// Setup for serial communication
Serial.begin(9600);
Serial.println("ESP32 collecting sensors data");
// Setup for LCD
lcd.init(); // initialize the lcd
lcd.backlight();
lcd.setCursor(1, 0);
lcd.print("ESP32 collecting data ...");
delay(1000);
// Setup for DHT sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(PIR_SENSOR, INPUT);
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() {
lcd.clear();
// Read data from DHT sensor
TempAndHumidity data = dhtSensor.getTempAndHumidity();
int temp = data.temperature;
int humid = data.humidity;
String stemp = String(temp) + "C";
String shumid = String(humid) + "%";
// Display data on LCD
lcd.setCursor(0, 0);
lcd.print("Temp: " + stemp);
lcd.setCursor(0, 1);
lcd.print("Humidity: " + shumid);
// Print data to Serial
Serial.println("Temp: " + stemp);
Serial.println("Humidity: " + shumid);
// Motion detection with PIR sensor
int pir_value = digitalRead(PIR_SENSOR);
if (pir_value == 1) {
digitalWrite(LED_PIN, HIGH);
Serial.println("Motion detected");
} else {
digitalWrite(LED_PIN, LOW);
Serial.println("Motion ended");
}
Serial.println("---");
if (WiFi.status() == WL_CONNECTED) {
// GET
HTTPClient http;
String serverPath = GET_METHOD + "?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();
// POST
http.begin(POST_METHOD);
http.addHeader("Content-Type", "application/json");
// char* httpRequestData;
// sprintf(httpRequestData, "{\"temp\": %f,\"humid\": %f }", stemp, shumid);
String httpRequestData = "{\"temp\": " + String(stemp) +",\"humid\": " + String(shumid) + "}";
Serial.println(httpRequestData);
httpResponseCode = http.POST(httpRequestData);
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(3000);
}