Ultrasonic Sensor:
VCC --> 5V on Nano
GND ---> GND on Nano
Trig ---> Digital Pin 2
Echo ---> Digital Pin 3
Servo Motor:
Power (Red) --->5V on Nano (Note: If your servo draws too much current, it should be powered by a separate 5V source with common ground)
Ground (Brown/Black) ---> GND on Nano
Signal (Yellow/Orange) ---> Digital Pin 9
#include <Servo.h>
// Define pins for the ultrasonic sensor
const int trigPin = 2;
const int echoPin = 3;
// Define pin for the servo motor
const int servoPin = 9;
Servo myServo; // Create servo object to control a servo
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Attach the servo on pin 9 to the servo object
myServo.attach(servoPin);
}
void loop() {
long duration;
int distance;
// 1. Send the Ultrasonic Pulse
// Clear the trigPin first
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// 2. Read the Echo
// Read the echoPin, returning the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
// Speed of sound is ~0.034 cm/microsecond. Divide by 2 for the round trip.
distance = duration * 0.034 / 2;
// 3. Process and Map the Value
// Clamp the distance to a maximum of 100cm so the servo doesn't over-rotate
distance = constrain(distance, 0, 100);
// Map the distance (0-100 cm) to servo angle (0-180 degrees)
int servoAngle = map(distance, 0, 100, 0, 180);
// Move the servo to the mapped angle
myServo.write(servoAngle);
// Print values to the Serial Monitor for troubleshooting
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm --> Servo Angle: ");
Serial.print(servoAngle);
Serial.println(" degrees");
// Small delay before the next reading to prevent signal bouncing/jitter
delay(50);
}