//a child safety lock to ensure no child gets outdoor without a elder accompaning them
//The height of the person opening the door is calculated based on the distance between the person and the sensor.
//The slide switch is used as the lock opener and the servo represents the state of the lock.
//A sms will be sent when child is trying to open the door.
#include <ESP32Servo.h> //including the libraries
#include <Ultrasonic.h>
#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include <SoftwareSerial.h>
// Ultrasonic Pins
int trigPin = 15;
int echoPin = 4;
Ultrasonic ultrasonic(trigPin, echoPin);
//adafruit credentials
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "Subi_7"
#define AIO_KEY "aio_dcLZ42uPJScT29nIqWYqEZ72xQ3m"
WiFiClient client;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
//setting up MQTT publish to send data to required feed in adafruit
Adafruit_MQTT_Publish send = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/notification_trigger");
// Servo Pin
int servoPin = 18;
Servo myServo;
void setup() {
Serial.begin(115200);//initiating the servo
myServo.attach(servoPin);
pinMode(21, INPUT_PULLUP);
Serial.print("Connecting to WiFi");//code to coonect to wifi
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
}
void connect() {// to connect to adafruit
Serial.print(F("Connecting to Adafruit IO... "));
int8_t ret;
while ((ret = mqtt.connect()) != 0) {
switch (ret) {
case 1: Serial.println(F("Wrong protocol")); break;
case 2: Serial.println(F("ID rejected")); break;
case 3: Serial.println(F("Server unavail")); break;
case 4: Serial.println(F("Bad user/pass")); break;
case 5: Serial.println(F("Not authed")); break;
case 6: Serial.println(F("Failed to subscribe")); break;
default: Serial.println(F("Connection failed")); break;
}
if(ret >= 0)
mqtt.disconnect();
Serial.println(F("Retrying connection..."));
delay(10000);
}
Serial.println(F("Adafruit IO Connected!"));
}
void loop() {
if(! mqtt.ping(3)) {
// reconnect to adafruit io
if(! mqtt.connected())
connect();
}
long distance = ultrasonic.read();
long Height = 400 - distance; //Measuring the height of the person
if(digitalRead(21)){
Serial.print("Height: ");
Serial.println(Height);
Serial.print(" cm");
if (!send.publish(static_cast<int32_t>(Height))) { //function to send data to adafruit //Publish to Adafruit
Serial.println(F("Failed"));
}else {
Serial.println(F("Sent!"));
}
if (Height >= 122) { // Check if height is more than 4 feet (122 cm)
myServo.write(90); // Unlock the door
Serial.println("Door Unlocked: The Person is taller than 4 feet.");
}else {
myServo.write(0); // Lock the door
Serial.println("Door Locked: Person not tall enough.");
}
}
delay(5000); // Delay before the next measurement
}