#include <Servo.h>
#include <NewPing.h> // Including Library for ultrasonic sensor
// Define pins and constants
int triggerPin = 4;
#define echoPin 3
#define maxDistance 400
NewPing varName(triggerPin, echoPin, maxDistance);
Servo myservo;
void setup() {
myservo.attach(9); // Attach the servo to pin 9
Serial.begin(9600);
}
void loop() {
// Read the distance from the ultrasonic sensor
delay(50); // Wait for a bit between pings
unsigned int distance = varName.ping_cm(); // Get distance in cm
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
// Map the distance to a servo angle
int angle = map(distance, 0, maxDistance, 90, 180);
angle = constrain(angle, 0, 180); // Make sure the angle is between 0 and 180
// Move the servo to the mapped angle
myservo.write(angle);
delay(100); // Small delay for smooth servo movement
}