#include <Servo.h>
// define pins for ultrasonic sensor
const int trigPin = 10;
const int echoPin = 11;
// define pin for servo
const int servoPin = 9;
// define variables for distance measurement
long duration;
int distance;
// create a servo object
Servo myServo;
void setup() {
// initialize serial communication
Serial.begin(9600);
// define the pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(servoPin, OUTPUT);
// attach the servo to the corresponding pin
myServo.attach(servoPin);
}
void loop() {
// generate a pulse to trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// measure the duration of the pulse from the ultrasonic sensor
duration = pulseIn(echoPin, HIGH);
// calculate the distance in centimeters
distance = duration * 0.034 / 2;
// print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// check if an object is detected within 50 centimeters
if (distance < 50) {
// rotate the servo to 90 degrees
myServo.write(180);
Serial.println("OPEN");
// wait for 5 seconds
delay(5000);
// measure the distance again
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// check if the object is still there
if (distance < 50) {
// keep the servo at 180 degrees
myServo.write(180);
Serial.println("OPEN");
} else {
// return the servo to the initial position
myServo.write(0);
Serial.println("CLOSED");
}
} else {
// return the servo to the initial position
myServo.write(0);
Serial.println("CLOSED");
}
// wait for some time before measuring the distance again
delay(500);
}