#include <Servo.h>
const int trigPin = 7;
const int echoPin = 6;
const int servoPin = 9;
Servo myServo;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.attach(servoPin);
myServo.write(0); // Start with the door closed
Serial.begin(9600);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
if (distance < 20) { // If an object is within 20 cm
myServo.write(90); // Open the door
} else {
myServo.write(0); // Close the door
}
delay(500);
}