// Include the necessary libraries
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#define BLYNK_TEMPLATE_ID "TMPL3wHK-n7GF"
#define BLYNK_TEMPLATE_NAME "Security Based System"
// Replace with your network credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Replace with your Blynk authentication token
const char* auth = "xV7-WVvCyC2b_cSK7vUSHKyP-E0-yrIH";
// Pin connected to the PIR sensor
const int pirPin = 15;
// Pin connected to the buzzer
const int buzzerPin = 2;
// Pin connected to the LED
const int ledPin = 4;
// Variable to store the previous state of the PIR sensor
int previousState = LOW;
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Connect to Blynk
Blynk.begin(auth, ssid, password);
Serial.println("Connected to Blynk");
// Configure PIR sensor pin
pinMode(pirPin, INPUT);
// Configure buzzer pin
pinMode(buzzerPin, OUTPUT);
noTone(buzzerPin);
// Configure LED pin
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Initialize the Blynk virtual pins
Blynk.virtualWrite(V1, LOW);
Blynk.virtualWrite(V2, LOW); // Set the LED initially to OFF state
#define BUZZER_STATUS_PIN V3 // Replace V3 with the desired virtual pin number
Blynk.virtualWrite(BUZZER_STATUS_PIN, LOW); // Set the initial status for the buzzer (LOW for OFF)
}
void loop() {
// Run Blynk
Blynk.run();
// Read the state of the PIR sensor
int currentState = digitalRead(pirPin);
// Check for motion detection
if (currentState == HIGH && previousState == LOW) {
// Motion detected
Serial.println("Motion detected!");
// Turn on the LED
digitalWrite(ledPin, HIGH);
Serial.println("Motion Detected");
// Activate the buzzer
tone(buzzerPin, 1000, 500);
// Send buzzer status to the Blynk app
Blynk.virtualWrite(BUZZER_STATUS_PIN, HIGH); // Set buzzer status to HIGH (ON)
// Send motion data to the Blynk app
Blynk.virtualWrite(V1, 1);
// Send LED control data to the Blynk app
Blynk.virtualWrite(V2, HIGH); // Set LED to ON state
} else if (currentState == LOW && previousState == HIGH) {
// Motion stopped
Serial.println("Motion stopped!");
// Turn off the LED
digitalWrite(ledPin, LOW);
// Send motion data to the Blynk app
Blynk.virtualWrite(V1, 0);
// Send LED control data to the Blynk app
Blynk.virtualWrite(V2, LOW); // Set LED to OFF state
// Deactivate the buzzer
noTone(buzzerPin);
// Send buzzer status to the Blynk app
Blynk.virtualWrite(BUZZER_STATUS_PIN, LOW); // Set buzzer status to LOW (OFF)
}
// Update the previous state
previousState = currentState;
}