#include <ESP32Servo.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
// Pin definitions
#define TRIG_PIN 14
#define ECHO_PIN 12
#define LED_PIN 19
#define SERVO_PIN 16
// WiFi and Telegram settings
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define BOT_TOKEN "7754609882:AAF3S8lKkh2Sz5WWDq6o37n74zsFo9_ufe8"
#define CHAT_ID "7012465456"
Servo servoMotor;
WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);
bool isDoorOpen = false;
float getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
return pulseIn(ECHO_PIN, HIGH) * 0.034 / 2;
}
void setup() {
Serial.begin(115200);
// Setup pins
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
// Setup servo
servoMotor.attach(SERVO_PIN);
servoMotor.write(90); // Start closed
// Connect WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
client.setInsecure();
bot.sendMessage(CHAT_ID, "System online!");
}
void loop() {
float distance = getDistance();
Serial.println("Distance: " + String(distance) + " cm");
// Door control logic
if (distance <= 100 && !isDoorOpen) {
servoMotor.write(0); // Open door
digitalWrite(LED_PIN, HIGH); // Turn on LED
bot.sendMessage(CHAT_ID, "🚪 Door opened");
isDoorOpen = true;
}
else if (distance > 100 && isDoorOpen) {
servoMotor.write(90); // Close door
digitalWrite(LED_PIN, LOW); // Turn off LED
bot.sendMessage(CHAT_ID, "🔒 Door closed");
isDoorOpen = false;
}
// Check for /status command
if (bot.getUpdates(bot.last_message_received + 1)) {
bot.sendMessage(CHAT_ID, "Distance: " + String(distance) + "cm\nDoor: " +
(isDoorOpen ? "Open" : "Closed"));
}
delay(1000); // Check every second
}