Home Industry InsightBLDC
Looking for a suitable motor? Looking for a suitable motor?
Looking for a suitable motor?

Mastering Distance Measurement with an Ultrasonic Sensor and Servo Motor Using Arduino

小编

Published2025-10-15

Discover how to control a servo motor with an ultrasonic sensor on an Arduino, creating an interactive distance-measuring system. This easy-to-follow guide will help you build a functional project while learning valuable skills in electronics and coding.

Arduino, Ultrasonic Sensor, Servo Motor, Arduino Code, Distance Measurement, DIY Electronics, Arduino Projects, Servo Control, Ultrasonic Technology, Sensor Integration

Getting Started with the Ultrasonic Sensor and Servo Motor

If you're diving into the world of Arduino, one of the most rewarding and straightforward projects you can start with is controlling a servo motor with the help of an ultrasonic sensor. This simple yet functional setup allows you to measure distances and move a servo motor based on those measurements. It's a fantastic way to enhance your skills in both hardware and software, making it an ideal beginner project.

What You’ll Need for the Project:

Before jumping into the code, let’s first take a look at the components you’ll need to complete this project:

Arduino Board (any Arduino model will work, such as Arduino Uno or Nano)

Ultrasonic Sensor (HC-SR04 is a popular choice)

Servo Motor (like the SG90 or MG90S)

Jumper Wires

Breadboard (optional for clean setup)

External Power Supply (if using a large servo motor)

Arduino IDE installed on your computer

Wiring the Components:

Wiring the components is straightforward, but it's important to get the connections right. Here's how to wire the ultrasonic sensor and servo motor to your Arduino:

Ultrasonic Sensor:

VCC Pin connects to 5V on Arduino.

GND Pin connects to the ground (GND) on Arduino.

Trig Pin connects to a digital I/O pin on the Arduino (e.g., Pin 9).

Echo Pin connects to another digital I/O pin (e.g., Pin 10).

Servo Motor:

VCC Pin connects to 5V on the Arduino (or external power supply).

GND Pin connects to the ground (GND).

Signal Pin connects to a PWM-capable digital I/O pin (e.g., Pin 11).

Understanding the Ultrasonic Sensor:

The ultrasonic sensor operates by emitting a sound pulse and then measuring the time it takes for the pulse to bounce back after hitting an object. This time delay is then used to calculate the distance between the sensor and the object using the speed of sound. The sensor works well in a variety of applications, including obstacle detection, distance measurement, and even robotic navigation.

Understanding the Servo Motor:

A servo motor is a small, precise motor that can rotate to specific angles based on a PWM (Pulse Width Modulation) signal. In this project, you will use the servo motor to move based on the distance measured by the ultrasonic sensor. Servo motors are commonly used in applications that require accurate positional control, such as robotic arms, camera pans, or even in this case, controlling the angle of a device based on real-world measurements.

Writing the Arduino Code:

Now, let’s jump into the fun part – coding! The goal is to write an Arduino script that reads the distance from the ultrasonic sensor and then adjusts the position of the servo motor based on that distance. Let’s break down the code into its major components.

Setting Up Libraries:

To control the servo motor, you'll need to include the Servo library in your code. This library simplifies the process of controlling servo motors, allowing you to focus on the distance measurement logic.

#include // Include Servo library

Pin Definitions:

Define the pins for both the ultrasonic sensor and the servo motor.

#define trigPin 9 // Pin for Trigger of Ultrasonic Sensor

#define echoPin 10 // Pin for Echo of Ultrasonic Sensor

#define servoPin 11 // Pin for Servo Motor

Creating Objects:

Create an instance of the Servo object and define variables to store distance measurements.

Servo myServo; // Create a Servo object

long duration, distance; // Variables to hold sensor data

Setting Up the Pins:

In the setup() function, initialize the pins for the ultrasonic sensor and the servo motor.

void setup() {

Serial.begin(9600); // Start serial communication

pinMode(trigPin, OUTPUT); // Set Trigger Pin as OUTPUT

pinMode(echoPin, INPUT); // Set Echo Pin as INPUT

myServo.attach(servoPin); // Attach the servo motor to the defined pin

}

Reading Distance and Controlling the Servo:

The loop() function will continuously measure the distance from the ultrasonic sensor, then map that distance to a servo motor position. The pulseIn() function is used to measure the duration of the pulse received by the echo pin.

void loop() {

digitalWrite(trigPin, LOW); // Ensure the trigger pin is low initially

delayMicroseconds(2);

digitalWrite(trigPin, HIGH); // Send a 10us HIGH pulse to trigger the sensor

delayMicroseconds(10);

digitalWrite(trigPin, LOW); // Stop sending the pulse

duration = pulseIn(echoPin, HIGH); // Measure the pulse duration

distance = duration * 0.0344 / 2; // Convert time to distance (cm)

// Print the distance to the Serial Monitor

Serial.print("Distance: ");

Serial.print(distance);

Serial.println(" cm");

// Map the distance to an angle (0 to 180 degrees)

int angle = map(distance, 0, 100, 0, 180); // Map distance to an angle for servo

myServo.write(angle); // Move the servo to the mapped angle

delay(500); // Wait before taking another reading

}

Testing the System:

After uploading the code to your Arduino board, open the Serial Monitor (Ctrl + Shift + M). You should see the measured distance in centimeters. As the distance changes, the servo motor will adjust its position accordingly.

Enhancing Your Ultrasonic Sensor and Servo Motor Project

With your basic system up and running, it's time to explore how to enhance and optimize your project. The combination of the ultrasonic sensor and the servo motor opens up a wide range of possibilities for more complex and interactive systems. In this section, we’ll dive into a few ways to improve your project.

1. Adding More Features with Multiple Servo Motors:

In the current setup, you're controlling a single servo motor based on the distance from the ultrasonic sensor. However, if you have multiple servo motors, you can use the same principle to control them independently. You’ll need to map different distances to different servos, creating a more dynamic system.

Servo myServo1, myServo2;

myServo1.attach(servoPin1);

myServo2.attach(servoPin2);

Then, you can add logic to control the movement of multiple servos based on the distance measured by the sensor. For example, the first servo might move to one position for short distances and the second servo to another position for longer distances.

2. Increasing Precision with More Sensors:

In some applications, you might need more accuracy or coverage. You can add multiple ultrasonic sensors to the system to scan a larger area. Each sensor could measure different directions or distances, feeding into the system to create a more precise control of the servo motors.

3. Handling Obstacles:

One interesting enhancement is integrating obstacle avoidance. For example, if your project involves a robot or automated system, you can program the servo motors to react to obstacles detected by the ultrasonic sensor. If the sensor detects an obstacle within a certain range, the system could automatically adjust the servo positions to avoid the obstacle, making your setup more interactive and responsive.

4. Powering the System:

If you plan to use larger servo motors, it's a good idea to use an external power supply. The Arduino board might not be able to provide enough current for powerful servos, especially under load. Use a separate 5V or 6V power supply for the servo motors, and connect the grounds of the power supply, Arduino, and servo motors to ensure a common reference.

5. Refining the Code for Efficiency:

As you progress with your project, it’s essential to optimize the code for efficiency. You can add conditional statements to limit the number of servo adjustments, reducing unnecessary movement. Additionally, consider adding a debounce function to smooth out any noisy data from the ultrasonic sensor, improving the stability of the servo's movement.

Conclusion:

This project combines fundamental electronics and programming skills to create an interactive and practical system that controls a servo motor based on the distance measured by an ultrasonic sensor. With this foundation, you can branch out into more advanced projects, such as building robotic arms, obstacle-avoiding robots, or even home automation systems. The flexibility and power of the Arduino platform provide endless opportunities for creativity and learning. Whether you're a beginner or a seasoned maker, this project is a great starting point to explore the endless possibilities of sensor integration and motor control.

Kpower has delivered professional drive system solutions to over 500 enterprise clients globally with products covering various fields such as Smart Home Systems, Automatic Electronics, Robotics, Precision Agriculture, Drones, and Industrial Automation.

Update:2025-10-15

Contact a motor expert for product recommendation.
Contact a motor expert for product recommendation.

Powering The Future

Contact Kpower's product specialist to recommend suitable motor or gearbox for your product.