#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <ESP32Servo.h>
#include <NewPing.h>
ESP32PWM pwm;
Servo servo;
// Wi-Fi credentials
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
// Blynk authentication token
#define BLYNK_TEMPLATE_ID "TMPL3pdjhb4cs"
#define BLYNK_TEMPLATE_NAME "Smart door system ESP32"
#define BLYNK_AUTH_TOKEN "q1BW-AcuJpOFYpNezLrv0hHSBCC8avQi"
char auth[] = BLYNK_AUTH_TOKEN;
// Pins for ultrasonic sensor
#define TRIGGER_PIN 4
#define ECHO_PIN 2
#define MAX_DISTANCE 20
// Pins for servo motor and buzzer
#define SERVO_PIN 12
#define BUZZER_PIN 33
// Blynk virtual pins
#define DOOR_STATUS_PIN V0
#define DISTANCE_PIN V1
// Variables
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
int doorStatus = 0;
void setup()
{
// Initialize Serial Monitor
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize Blynk
Blynk.begin(auth, ssid, pass, "blynk.cloud", 80);
Serial.println("after blynk begin");
// Initialize servo and set initial position
servo.attach(SERVO_PIN);
servo.write(90);
// Set buzzer pin as output
pinMode(BUZZER_PIN, OUTPUT);
}
void loop()
{
Blynk.run();
checkDistance();
}
void checkDistance()
{
// Read distance from the ultrasonic sensor
int distance = sonar.ping_cm();
// Update Blynk with the distance value
Blynk.virtualWrite(DISTANCE_PIN, distance);
// Check if someone is approaching the door too closely (adjust threshold as needed)
if (distance < 20)
{
activateBuzzer();
}
}
void activateBuzzer()
{
// Sound the buzzer for a short duration
tone(BUZZER_PIN, 1000, 500);
}
BLYNK_WRITE(DOOR_STATUS_PIN)
{
Serial.println("in blynk write");
// Update the door status variable
doorStatus = param.asInt();
// Control the servo motor based on the door status
if (doorStatus == 20)
{
servo.write(90); // Open the door (adjust angle as needed)
}
else
{
servo.write(0); // Close the door
}
}