#include <Servo.h>
Servo myServo;
// Ultrasonic sensor pins
const int trigPin = 5;
const int echoPin = 6;
// Distance threshold (in cm)
const int distanceThreshold = 10;
void setup() {
Serial.begin(9600);
myServo.attach(9); // Connect servo to pin 6
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.write(0); // Initial servo position
}
void loop() {
long duration;
int distance;
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo time
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Rotate servo if object is detected
if (distance > 0 && distance < distanceThreshold) {
myServo.write(90); // Rotate to 90 degrees
} else {
myServo.write(0); // Return to 0 degrees
}
delay(500);
}
No comments:
Post a Comment