#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
#include <WiFi.h>
#include <ThingSpeak.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
long myChannelNumber = 2729019;
const char *myWriteAPIKey = "CL9YNLVFSCQBW2L0";
int statusCode;
const int pirPin = 2; // PIR motion sensor pin
const int greenLedPin = 12; // Green LED pin
const int redLedPin = 13; // Red LED pin
const int buzzerPin = 4; // Buzzer pin
const int lcdColumns = 21; // LCD column size
const int lcdRows = 2; // LCD row size
int R = 0, B = 0, M = 0; // Variables for ThingSpeak fields
bool doorClosed = false; // Flag to track if door is closed
LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); // Initialize LCD
Servo servo; // Initialize Servo object
void setup() {
pinMode(pirPin, INPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
servo.attach(18); // Attach servo to pin 18
servo.write(90); // Set servo to 90 degrees (open door)
Serial.begin(115200); // Start serial communication
WiFi.mode(WIFI_STA); // Set WiFi to station mode
ThingSpeak.begin(client); // Initialize ThingSpeak
lcd.init(); // Initialize LCD
lcd.backlight(); // Turn on LCD backlight
lcd.print("Door open");
delay(2000); // Initial display time
}
void connectWiFi() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect to WiFi");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("\nConnected to WiFi.");
}
}
void loop() {
connectWiFi(); // Ensure WiFi is connected
delay(5000); // Give time for any pending WiFi connections
// Check PIR sensor state
int pirState = digitalRead(pirPin);
Serial.println("PIR State: " + String(pirState)); // Debugging output
if (pirState == HIGH && !doorClosed) { // Motion detected and door not yet closed
doorClosed = true; // Set door to closed state
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Motion Detected!");
digitalWrite(redLedPin, HIGH); // Turn on red LED (indicating alarm)
tone(buzzerPin,0); // Activate buzzer at 500Hz
servo.write(0); // Move servo to 0 degrees (close door)
lcd.setCursor(0, 1);
lcd.print("Door Closed");
// Update status for ThingSpeak
R = 1; // Red LED on
B = 1; // Buzzer on
M = 1; // Motion detected
}
// Update ThingSpeak fields with sensor data
ThingSpeak.setField(1, B); // Field 1: Buzzer status (0 or 1)
ThingSpeak.setField(2, M); // Field 2: Motion detection status (0 or 1)
ThingSpeak.setField(3, R); // Field 3: Red LED status (0 or 1)
// Write data to ThingSpeak
statusCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (statusCode == 200) {
Serial.println("Channel update successful.");
} else {
Serial.println("Problem writing to channel. HTTP error code: " + String(statusCode));
}
delay(5000); // Wait for 5 seconds before the next loop
}