#include <Servo.h>

const int trigPin = 8;
const int echoPin = 9;
const int servoPin = 11;
const int distanceThreshold = 20; // Distance threshold in cm

Servo myServo;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  myServo.attach(servoPin);
}

void loop() {
  // Send a pulse to trigger pin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the pulse from echo pin
  long duration = pulseIn(echoPin, HIGH);
  int distance = duration * 0.034 / 2; // Convert to cm

  if (distance <= distanceThreshold) {
    // Rotate servo forward
    myServo.write(180);
    delay(1000); // Hold for 1 second
    // Rotate servo backward
    myServo.write(0);
    delay(1000); // Hold for 1 second
  } else {
    // Stop servo at 90 degrees (neutral position)
    myServo.write(90);
  }

  delay(200); // Short delay before next reading
}
