Project 2.9.1: Servo Motor Control with Ultrasonic Sensor
| Description | This project demonstrates how to interface an Ultrasonic distance sensor with a Servo motor. The servo motor's shaft rotates to specific angles depending on the proximity of an object detected by the ultrasonic sensor. |
|---|---|
| Use case | This system forms the basis for obstacle-avoiding steering in robotics, automatic gate openers that swing open when a vehicle approaches, and visual gauge indicators. |
Learning Objectives
- Understand how to read distance data from an Ultrasonic Sensor.
- Learn how to include and utilize the
Servolibrary to control a servo motor. - Apply the
map()function to convert distance values (e.g., 2cm to 30cm) into motor angles (0° to 180°).
Components (Things You will need)
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|
Things Needed:
- Arduino Uno = 1
- Arduino USB Cable = 1
- Breadboard = 1
- HC-SR04 Ultrasonic Sensor = 1
- Servo Motor (e.g., SG90) = 1
- Male-to-Male Jumper Wires = 8
Building the Circuit
Step 1: Mount the Components
- Insert the Ultrasonic Sensor into the breadboard so that its four pins (VCC, Trig, Echo, GND) sit in separate columns.
- Connect the Servo Motor wiring harness. The SG90 servo motor has three colored wires:
- Brown = Ground (GND)
- Red = Power (5V)
- Orange/Yellow = Signal (PWM control)
Wiring the Circuit
Follow the connections below to wire the sensors and motor to the Arduino Uno:
| Component | Pin Name | Arduino Uno Pin | Wire Color (Recommended) |
|---|---|---|---|
| Ultrasonic Sensor | VCC | 5V | Red |
| Trig | Pin 2 | Yellow | |
| Echo | Pin 3 | Green | |
| GND | GND | Black | |
| Servo Motor | GND (Brown) | GND | Black/Brown |
| VCC (Red) | 5V | Red | |
| Signal (Orange) | Pin 9 | Orange |
[!TIP] Since both the Ultrasonic Sensor and the Servo Motor require connection to the 5V power pin and GND, use the breadboard's power rails. Connect the Arduino Uno 5V pin to the red (+) rail, and the Arduino GND pin to the blue (-) rail. Then, connect VCC and GND of both devices to these rails.
Programming
Step 1: Open your Arduino IDE. Make sure your Arduino Uno is connected.
Step 2: Write or copy the following code into the editor.
#include <Servo.h> // Include the standard Servo library
// Define Ultrasonic Sensor Pin connections
const int trigPin = 2;
const int echoPin = 3;
// Define Servo Pin connection
const int servoPin = 9;
// Create a servo object to control the motor
Servo myServo;
// Variables to store pulse duration and distance
long duration;
int distance;
int servoAngle;
void setup() {
// Initialize Serial Monitor for debugging
Serial.begin(9600);
// Set pin modes for the Ultrasonic Sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Attach the servo motor object to its control pin
myServo.attach(servoPin);
// Set the servo to its initial position (0 degrees)
myServo.write(0);
}
void loop() {
// Clear the trigger pin to ensure a clean pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send a 10-microsecond pulse to trigger distance measurement
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin pulse duration (in microseconds)
duration = pulseIn(echoPin, HIGH);
// Calculate distance in centimeters
// (Duration is divided by 2 to account for travel time to the object and back)
distance = duration * 0.034 / 2;
// Print the distance values to the Serial Monitor for observation
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm -> ");
// Limit distance readings to a stable sensing range (2cm to 30cm)
if (distance > 30) {
distance = 30;
}
if (distance < 2) {
distance = 2;
}
// Map the distance (2cm to 30cm) to servo angle (0 to 180 degrees)
// Closer distance = higher angle (e.g., warning state or physical block)
// Farther distance = lower angle
servoAngle = map(distance, 2, 30, 180, 0);
// Command the servo to rotate to the mapped angle
myServo.write(servoAngle);
Serial.print("Servo Angle: ");
Serial.println(servoAngle);
// Small delay to allow the servo to reach the position and stabilize readings
delay(100);
}
Uploading the code
- Verify your board type is set to Arduino Uno by navigating to
Tools -> Board -> Arduino AVR Boards -> Arduino Uno. - Select the correct serial port under
Tools -> Port. - Click the Upload button (right-pointing arrow icon) to flash the code onto the board.
- Open the Serial Monitor (
Tools -> Serial MonitororCtrl+Shift+M) at 9600 baud to see real-time distance and angle feedback.
Expected Outcome
When you wave your hand or place an object in front of the Ultrasonic Sensor: * As the object moves closer (towards 2cm), the servo motor rotates towards 180 degrees. * As the object moves farther away (towards 30cm), the servo motor returns towards 0 degrees. * If no object is within 30cm, the servo remains at 0 degrees.
Troubleshooting
- Servo motor twitches but does not rotate: This is usually a power issue. Ensure the servo is connected directly to the Arduino's 5V pin (and not 3.3V). Check that all jumper wire connections on the breadboard are firm.
- Distance readings are constant or read 0: Make sure the Trig and Echo pins are not reversed. Verify that Trig is connected to Pin 2 and Echo to Pin 3.
- Servo moves in the opposite direction: If you want the servo to move towards 0 degrees as an object gets closer, change the
mapfunction parameters frommap(distance, 2, 30, 180, 0)tomap(distance, 2, 30, 0, 180).




