#include <Servo.h>
const int trigPin = 9; // Pin for the trig pin of the HC-SR04
const int echoPin = 10; // Pin for the echo pin of the HC-SR04
const int servoPin = 11; // Pin for the servo signal
Servo myServo; // Create a servo object
const int distanceThreshold = 20; // Distance threshold in cm
void setup() {
Serial.begin(9600); // Start the serial communication
pinMode(trigPin, OUTPUT); // Set the trigPin as an output
pinMode(echoPin, INPUT); // Set the echoPin as an input
myServo.attach(servoPin); // Attach the servo to the servoPin
myServo.write(0); // Initial position of the servo
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
if (distance <= distanceThreshold) {
myServo.write(90); // Rotate servo to 90 degrees
} else {
myServo.write(0); // Rotate servo back to 0 degrees
}
delay(500); // Wait for half a second before the next loop
}