#include <Servo.h>
// Pin definitions
const int trigPin = 5;
const int echoPin = 4;
const int buzzerPin = 12;
const int servoPin = 6;
// Ultrasonic variables
long duration;
int distance;
// Servo variables
Servo myservo;
int pos = 0; // Current servo position
int direction = 1; // 1 for increasing, -1 for decreasing
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
myservo.attach(servoPin);
myservo.write(pos); // Initialize servo position
}
void loop() {
// Move servo
pos += direction;
myservo.write(pos);
// Change direction when reaching limits
if (pos >= 180 || pos <= 0) {
direction *= -1;
}
// Measure distance
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Control buzzer based on distance
if (distance < 25 && distance > 0) {
digitalWrite(buzzerPin, HIGH);
} else {
digitalWrite(buzzerPin, LOW);
}
// Delay for smooth servo movement and sensor stability
delay(15);
}