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

How to Use a Servo and Ultrasonic Sensor with Arduino: A Comprehensive Guide

小编

Published2025-10-15

Introduction to Servo Motors and Ultrasonic Sensors

The Arduino platform has become a go-to solution for DIY enthusiasts and hobbyists looking to build electronic projects. Whether you're a beginner or a seasoned pro, one of the most exciting aspects of using Arduino is its ability to control various types of sensors and motors. In this guide, we will focus on combining two of the most commonly used components: the servo motor and the ultrasonic sensor.

A servo motor is a small, powerful device used for precise angular movements. Unlike regular DC motors, which continuously rotate when powered, a servo motor can be controlled to rotate to a specific angle. This makes it ideal for applications like robotic arms, camera pans, or controlling the position of a device.

The ultrasonic sensor, on the other hand, uses sound waves to measure distance. It has two primary components: a transmitter that sends out a sound wave and a receiver that detects the echo as it returns. By measuring the time it takes for the sound to travel, the sensor can calculate the distance to an object. This makes it extremely useful in robotics, obstacle detection, and distance measurement applications.

Materials You Will Need:

Arduino board (e.g., Arduino Uno)

Servo motor

Ultrasonic sensor (e.g., HC-SR04)

Jumper wires

Breadboard (optional, for organizing connections)

External power supply (for larger servo motors)

Setting Up the Components

Before diving into the coding part, it’s essential to connect the hardware correctly. Here's how you should wire the components:

1. Connecting the Servo Motor

Servo Motor Pins:

Red wire (Power): Connect this to the 5V pin on the Arduino.

Brown wire (Ground): Connect this to the GND pin on the Arduino.

Orange/Yellow wire (Control): Connect this to a PWM-enabled pin on the Arduino, such as Pin 9.

2. Connecting the Ultrasonic Sensor (HC-SR04)

Ultrasonic Sensor Pins:

VCC: Connect this to the 5V pin on the Arduino.

GND: Connect this to the GND pin on the Arduino.

Trig: Connect this to a digital pin (e.g., Pin 12) on the Arduino.

Echo: Connect this to another digital pin (e.g., Pin 11) on the Arduino.

The wiring is pretty straightforward and ensures that the sensor and the servo motor are powered correctly. Once you have everything connected, it's time to focus on the software part.

Writing the Arduino Code for Servo and Ultrasonic Sensor Control

Now that we’ve set up the hardware, it’s time to write the code to control both the servo motor and the ultrasonic sensor. The goal is to have the ultrasonic sensor measure the distance of an object and use that information to control the position of the servo motor.

Understanding the Code Structure

Including Libraries:

To control the servo motor and ultrasonic sensor, you’ll need to include the relevant libraries. The Servo library comes pre-installed in the Arduino IDE, but you may need to install a library for the ultrasonic sensor if you're using advanced features. However, in this case, we’ll be using a basic example with no extra libraries for the sensor.

Pin Definitions:

We’ll define the pins that the servo motor and ultrasonic sensor are connected to. These will be the basis for controlling the components via code.

Measuring Distance:

The ultrasonic sensor works by sending out a pulse from the Trig pin and then waiting for the pulse to return on the Echo pin. The time taken for this return will help us calculate the distance.

Controlling the Servo:

Based on the distance measurement, we can control the servo motor’s angle. For instance, if an object is detected at a distance of 10 cm, the servo motor could rotate to a specific angle (e.g., 90 degrees).

Example Arduino Code:

#include

// Pin definitions

const int trigPin = 12;

const int echoPin = 11;

const int servoPin = 9;

// Servo object

Servo myServo;

void setup() {

// Initialize servo motor

myServo.attach(servoPin);

// Set ultrasonic sensor pins

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

// Start serial communication for debugging

Serial.begin(9600);

}

void loop() {

// Send a pulse to trigger the sensor

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

// Measure the pulse duration

long duration = pulseIn(echoPin, HIGH);

// Calculate the distance in cm

long distance = (duration / 2) / 29.1; // Speed of sound = 343 meters per second

// Print the distance for debugging

Serial.print("Distance: ");

Serial.println(distance);

// Control the servo based on the distance

if (distance <= 10) {

myServo.write(90); // Move to 90 degrees if object is within 10 cm

} else {

myServo.write(0); // Move to 0 degrees if object is farther

}

// Wait a bit before the next reading

delay(500);

}

Breaking Down the Code:

Servo Control:

We create a Servo object called myServo.

The myServo.attach(servoPin) function links the servo to the specified pin (Pin 9).

myServo.write(angle) is used to control the servo’s angle, where angle can be between 0 and 180.

Ultrasonic Sensor:

The digitalWrite(trigPin, HIGH) sends a short pulse to the trigger pin to start the measurement.

The pulseIn(echoPin, HIGH) function listens for the echo and calculates the time it took for the sound wave to return.

Using the formula distance = (duration / 2) / 29.1, we convert the time taken to distance (in centimeters). The division by 29.1 comes from the speed of sound in air.

Servo Movement Based on Distance:

If the measured distance is less than or equal to 10 cm, the servo rotates to 90 degrees.

If the object is farther than 10 cm, the servo moves to 0 degrees.

Serial Monitor:

The Serial.print() and Serial.println() functions are used for debugging, printing the measured distance to the Serial Monitor.

Testing and Calibration

Once you’ve uploaded the code to your Arduino board, you should start seeing values of distance in the Serial Monitor. The servo will move based on the proximity of an object to the ultrasonic sensor.

You can calibrate the behavior by adjusting the distance threshold and the servo angles in the code.

Experiment with the servo’s range of motion and adjust the angle for different distances as needed.

This basic setup can be used in a variety of applications, from robotics to obstacle avoidance systems. By tweaking the code and adding more sensors or motors, you can create more complex systems that respond dynamically to their environment.

This concludes Part 2 of this guide. With the servo motor and ultrasonic sensor set up and the code ready, you can start experimenting and building your own interactive projects with Arduino!

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.