#include <Servo.h> // Include the Servo library
#define SERVO_PIN 9 // Define the pin for the servo motor signal
#define LED_PIN 13 // Define the pin for the LED
#define TRIG_PIN 3 // Define the pin for the ultrasonic sensor trigger
#define ECHO_PIN 2 // Define the pin for the ultrasonic sensor echo
Servo servo; // Create a Servo object to control the servo motor
int pos = 0; // Variable to store the servo position
void setup() {
pinMode(LED_PIN, OUTPUT); // Set the LED pin as an output
pinMode(TRIG_PIN, OUTPUT); // Set the TRIG_PIN as an output
pinMode(ECHO_PIN, INPUT); // Set the ECHO_PIN as an input
servo.attach(SERVO_PIN); // Attach the servo motor to pin 9
Serial.begin(9600); // Initialize serial communication for debugging
}
void loop() {
// Trigger the ultrasonic sensor to send out a pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the pulse duration from the sensor
float duration_us = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm
float distance_cm = 0.017 * duration_us;
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
if (distance_cm < 20) {
// Rotate the servo from 0 to 45 degrees
for (pos = 0; pos <= 45; pos += 1) {
servo.write(pos); // Move the servo to the current position
delay(10); // Wait 10ms for the servo to reach the position
}
delay(500); // Add delay after reaching 45 degrees
digitalWrite(LED_PIN, HIGH); // Turn on the LED when the servo is at 45 degrees
} else {
// Rotate the servo from 45 to 180 degrees
for (pos = 45; pos <= 180; pos += 1) {
servo.write(pos); // Move the servo to the current position
delay(10); // Wait 10ms for the servo to reach the position
}
delay(500); // Add delay after reaching 180 degrees
digitalWrite(LED_PIN, LOW); // Turn off the LED when the servo is at 180 degrees
}
delay(1000); // Additional delay before the next loop iteration
}