const int trigPin = 7;    // Trig pin of the ultrasonic sensor

const int echoPin = 6;   // Echo pin of the ultrasonic sensor

const int servoPin = 2;  // Signal pin of the servo motor

const int switchPin = 3;  // Pin for the switch

 

#include <Servo.h>

Servo myservo;  // Declaring Servo object

 

void setup() {

  Serial.begin(9600);

  pinMode(trigPin, OUTPUT);

  pinMode(echoPin, INPUT);

  pinMode(switchPin, INPUT_PULLUP); // Internal pull-up resistor for the switch pin

  myservo.attach(servoPin); // Attaching servo to servoPin

}

 

void loop() {

  // Check if the switch is on

  if (digitalRead(switchPin) == HIGH) {

    long duration, distance;

 

    // Clear the trigPin

    digitalWrite(trigPin, LOW);

    delayMicroseconds(2);

   

    // Trigger the sensor by sending a 10us HIGH pulse

    digitalWrite(trigPin, HIGH);

    delayMicroseconds(10);

    digitalWrite(trigPin, LOW);

   

    // Read the duration of the echo pulse

    duration = pulseIn(echoPin, HIGH);

   

    // Calculate distance in centimeters

    distance = duration * 0.034 / 2;

 

    Serial.print("Distance: ");

    Serial.print(distance);

    Serial.println(" cm");

 

    // If distance is below a certain threshold, activate the servo

    if (distance < 50) { // Adjust the threshold as needed

      // Map the distance to the servo angle (0-180)

      int angle = map(distance, 0, 200, 0, 180);

     

      // Limit the angle within 0-180

      angle = constrain(angle, 0, 180);

 

      // Move the servo to the calculated angle

      myservo.write(angle);

     

      delay(100); // Adjust delay as needed for your application

    }

  }

 

  // Add a small delay to avoid overwhelming the serial port

  delay(100); // Adjust delay as needed for your application

}

 