// Include the necessary libraries
#include <Servo.h>
// Define the pins for the HC-SR04 sensor
#define TRIGGER_PIN 2
#define ECHO_PIN 3
// Define the servo pin
#define SERVO_PIN 9
// Define the maximum distance for object detection in cm
#define MAX_DISTANCE 10
// Initialize the servo object
Servo servo;
// Initialize variables for object detection and servo rotation
int objectCount = 0;
int servoAngle = 0;
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Set the trigger pin as output and echo pin as input
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Attach the servo to the servo pin
servo.attach(SERVO_PIN);
// Set the initial servo angle to 0 degrees
servo.write(servoAngle);
}
void loop() {
// Send a pulse to the trigger pin to start the measurement
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Read the duration of the pulse from the echo pin
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance in cm
int distance = duration * 0.034 / 2;
// Check if an object is detected within the maximum distance
if (distance <= MAX_DISTANCE) {
// Increase the object count
objectCount++;
// Print the distance and object count for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm, Object Count: ");
Serial.println(objectCount);
// Check if the object count is equal to 3
if (objectCount == 3) {
// Rotate the servo to 90 degrees in 1 seconds
servo.write(90);
delay(1000);
// Reset the object count to 0
objectCount = 0;
}
} else {
// Reset the object count to 0 if no object is detected
objectCount = 0;
}
}