#include <Servo.h>
// Define the pins for the ultrasound sensor
const int trigPin = 8; // Trigger pin
const int echoPin = 9; // Echo pin
// Define the pin for the servo motor
const int servoPin = 7; // Servo motor pin
// Create a Servo object
Servo myServo;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Define the pins as input or output
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Attach the servo to its pin
myServo.attach(servoPin);
}
void loop() {
// Clear the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse to trigger the sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse returned by the sensor
long duration = pulseIn(echoPin, HIGH);
// Calculate distance in centimeters
int distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if distance is less than 25 cm
if (distance < 25) {
// If distance is less than 25 cm, rotate the servo motor
myServo.write(90); // Rotate servo to 90 degrees
delay(500); // Wait for the servo to reach its position
} else {
// If distance is greater than or equal to 25 cm, stop the servo motor
myServo.write(0); // Rotate servo to 0 degrees
}
// Wait a short delay before taking the next reading
delay(1000);
}