// Include libraries at the beginning
#include <Servo.h>
// Define your variables
const int trigPin = A0; // Pin for the HC-SR04 trigger
const int echoPin = A1; // Pin for the HC-SR04 echo
Servo motor; // Create a Servo object to control the motor
int motorPin = A2; // Pin for the servo motor
long duration; // Variable to store the time it takes for sound to return
int distance; // Variable to store the calculated distance
void setup() {
// Setup pins and start the motor object
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
motor.attach(motorPin);
// Initialize the motor to a neutral position
motor.write(90); // 90 degrees = motor is stationary
Serial.begin(9600); // Start serial monitor for debugging
}
void loop() {
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read echo time
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
// Print distance to serial monitor for debugging
Serial.print("Distance: ");
Serial.println(distance);
// Check if distance is less than 100 cm
if (distance < 100) {
// Move the motor to 180 degrees
motor.write(180);
} else {
// Move the motor back to 90 degrees
motor.write(90);
}
delay(10); // Delay for stability
}