#include <Servo.h>
const int trigPin = 9;
const int echoPin = 10;
const int servoPin = 11;
const int distanceThreshold = 10; // Distance threshold in cm
long duration;
int distance;
Servo myServo; // Create a servo object to control the servo
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
myServo.attach(servoPin); // Attach the servo on pin 11 to the servo object
Serial.begin(9600); // Start the serial communication
myServo.write(0); // Set initial position of the servo to 0 degrees
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, return the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than the threshold
if (distance <= distanceThreshold) {
myServo.write(170); // Rotate servo to 90 degrees
} else {
myServo.write(0); // Rotate servo back to 0 degrees
}
delay(500); // Wait for half a second before the next loop
}
No comments:
Post a Comment