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

Mastering Motion and Distance: A Guide to Using Servo Motors and Ultrasonic Sensors with Arduino

小编

Published2025-09-16

Introduction to Servo Motors and Ultrasonic Sensors

The marriage of servo motors and ultrasonic sensors opens a world of possibilities for Arduino enthusiasts. Whether you’re building a robot, a smart security system, or an interactive art installation, these two components work together to detect obstacles and control motion with precision. In this guide, you’ll learn how to wire, program, and innovate using these tools.

Why Servo Motors and Ultrasonic Sensors?

Servo Motors: Unlike standard motors, servos offer precise angular control (0–180 degrees), making them ideal for steering mechanisms, robotic arms, or automated doors. Ultrasonic Sensors: The HC-SR04 sensor measures distance using sound waves, providing accurate readings from 2 cm to 400 cm. It’s perfect for collision avoidance, object detection, and interactive installations.

Components You’ll Need

Arduino Uno or Nano HC-SR04 ultrasonic sensor SG90 micro servo motor Jumper wires Breadboard USB cable

Setting Up the Hardware

Step 1: Wiring the Ultrasonic Sensor The HC-SR04 has four pins:

VCC → 5V on Arduino GND → GND on Arduino Trig → Digital Pin 9 Echo → Digital Pin 10

Step 2: Connecting the Servo Motor The SG90 servo has three wires:

Brown (GND) → GND on Arduino Red (VCC) → 5V on Arduino Yellow (Signal) → Digital Pin 6

Step 3: Power Management Use a breadboard to distribute power. Avoid powering the servo directly from Arduino if using high-torque models; consider an external supply.

Writing the Basic Code

Let’s create a program that sweeps the servo based on distance measurements.

```cpp

include

Servo myServo; const int trigPin = 9; const int echoPin = 10;

void setup() { myServo.attach(6); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); Serial.begin(9600); }

void loop() { long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH); distance = (duration * 0.0343) / 2; // Convert to centimeters

if (distance < 20) { myServo.write(90); // Rotate to 90 degrees if object is close } else { myServo.write(0); // Return to 0 degrees }

Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); delay(100); }

#### Testing the Setup Upload the code and observe the servo’s behavior. When an object is within 20 cm, the servo moves to 90 degrees. Otherwise, it stays at 0 degrees. Use the Serial Monitor to debug distance values. #### Troubleshooting Tips - Servo Jitters: Ensure stable power supply; add a capacitor (100µF) between VCC and GND. - Incorrect Distance Readings: Check for obstructions, and ensure the sensor faces the target directly. --- ### #### Advanced Project: Automated Obstacle-Avoiding System Now that you’ve mastered the basics, let’s build a system where a servo-mounted ultrasonic sensor scans the environment and reacts to obstacles. #### Concept Overview - The servo sweeps from 0 to 180 degrees. - At each angle, the ultrasonic sensor measures distance. - If an obstacle is detected within 30 cm, the servo stops and triggers an action (e.g., LED alert or motor reversal). #### Enhanced Wiring Setup - Keep the previous connections. - Add an LED to Digital Pin 7 (optional for visual feedback). #### Writing the Scanning Code

cpp

include

Servo scannerServo; const int trigPin = 9; const int echoPin = 10; const int ledPin = 7; int pos = 0;

void setup() { scannerServo.attach(6); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(ledPin, OUTPUT); Serial.begin(9600); }

void loop() { for (pos = 0; pos <= 180; pos += 10) { scannerServo.write(pos); delay(50); long distance = getDistance(); Serial.print("Angle: "); Serial.print(pos); Serial.print("°, Distance: "); Serial.print(distance); Serial.println(" cm");

if (distance < 30) { digitalWrite(ledPin, HIGH); delay(1000); // Alert for 1 second digitalWrite(ledPin, LOW); }

} for (pos = 180; pos >= 0; pos -= 10) { scannerServo.write(pos); delay(50); // Repeat distance check (optional) } }

long getDistance() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); long duration = pulseIn(echoPin, HIGH); return (duration * 0.0343) / 2; } ```

Real-World Applications

Robotics: Create a robot that navigates around obstacles. Smart Home: Automate windows or blinds to close when objects approach. Security Systems: Detect intruders and trigger alarms or cameras.

Optimizing Performance

Reduce Noise: Use pulseIn() with a timeout or average multiple readings. Power Efficiency: Put the sensor to sleep when idle. 3D Scanning: Mount the sensor on a dual-axis servo for spatial mapping.

Conclusion and Next Steps

You’ve now unlocked the potential of combining servo motors and ultrasonic sensors with Arduino. Experiment with integrating additional components like LCDs, buzzers, or Bluetooth modules. Share your projects online to inspire others!

This guide equips you with the skills to turn distance data into motion, bridging the gap between sensing and action. Whether for hobbyist fun or prototyping professional systems, the servo-ultrasonic duo is your gateway to smarter automation.

Update:2025-09-16

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.