#include <DHT.h>
#include <LiquidCrystal.h>
#include <WiFi.h>
#include<HTTPClient.h>
const int DHTPIN = 12;
int PirPin = 33;
int pirState = LOW;
int val = 0;
const int RS=4, E = 15, DB4 = 5, DB5 = 18, DB6 = 21, DB7 = 22;
LiquidCrystal lcd (RS,E,DB4,DB5,DB6,DB7);
int hum;
int temp;
DHT dht (DHTPIN, DHT22);
long lastTime = 0;
long timerDelay = 500;
const char ssid[] = "Wokwi-GUEST";
const char password[] = "";
String serverName = "https://api.thingspeak.com/update?api_key=VSZB6AL45UYE9ZM9";
int motionState;
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(PirPin, INPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print ("-");
}
Serial.println("");
Serial.print ("ESP 32 Connected\n");
Serial.println(WiFi.localIP());
lcd.begin(16,2);
motionState= LOW;
dht.begin();
}
void loop(){
if ((millis() - lastTime) > timerDelay){
if (WiFi.status() == WL_CONNECTED){
val = digitalRead(PirPin);
hum = dht.readHumidity();
temp = dht.readTemperature();
//lcd.clear();
display (temp, hum);
if (val == HIGH)
{
if (pirState == LOW)
{
Serial.println("\nMotion detected!");
//Serial.println(pirState);
motionState = HIGH;
sendData(temp, hum, motionState);
pirState = HIGH;
lcd.setCursor(0,1);
lcd.print ("Motion detected!");
}
}
else
{
if (pirState == HIGH)
{
delay(5000);
Serial.println("\nMotion ended!");
//Serial.println(pirState);
motionState = LOW;
sendData(temp, hum, motionState);
pirState = LOW;
lcd.setCursor(0,1);
lcd.print ("Motion ended! ");
}
}
//Serial.println(pirState);
sendData(temp, hum, motionState);
}
else{
Serial.println("Wifi Disconnected");
}
lastTime = millis();
}
//Serial.println("-----");
//delay(2000);
}
void display (int temp, int hum){
Serial.print ("\nHumidity: ");
Serial.print (hum);
Serial.print ("\tTemperature: ");
Serial.print(temp);
lcd.setCursor(0,0);
lcd.print ("Hum: ");
lcd.print(hum);
lcd.print ("\tTemp: ");
lcd.print(temp);
lcd.setCursor(0,1);
lcd.print (" ");
}
void sendData ( int temp, int hum, int motionState){
HTTPClient http;
Serial.print("\nMotion: ");
Serial.println(motionState);
String url = serverName + "&field1=" + hum + "&field2=" + temp + "&field3=" + motionState;
http.begin(url.c_str());
int httpResponseCode = http.GET();
if (httpResponseCode>0){
Serial.print ("\nHTTP Response Code: ");
Serial.println(httpResponseCode);
}
else{
Serial.print ("Error Code");
Serial.println(httpResponseCode);
}
http.end();
//delay(3000);
}