#include <Servo.h>
const int trigPin = 9; // Trigger pin of the ultrasonic sensor
const int echoPin = 10; // Echo pin of the ultrasonic sensor
Servo myServo; // Servo object
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.attach(11); // Connect the servo to pin 11
}
void loop() {
// Measure distance using ultrasonic sensor
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;
// Print distance to Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Move the servo based on distance
if (distance < 10) { // If the object is closer than 10 cm
myServo.write(0); // Move the servo to 0 degrees
} else if (distance > 30) { // If the object is farther than 30 cm
myServo.write(180); // Move the servo to 180 degrees
} else {
// Map the distance value to servo angle between 0 and 180 degrees
int servoAngle = map(distance, 10, 30, 0, 180);
myServo.write(servoAngle); // Move the servo to the calculated angle
}
delay(500); // Wait for a short duration before the next measurement
}