Raspberry Pi - Ultrasonic Sensor - Servo Motor

This tutorial instructs you how to use Raspberry Pi and ultrasonic sensor to control servo motor. In detail:

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Ultrasonic Sensor
1×Servo Motor
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) USB-C Power Cable with On/Off Switch for Raspberry Pi 4B
1×(Optional) Plastic Case and Cooling Fan for Raspberry Pi 4B

Or you can buy the following sensor kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.

Overview of Servo Motor and Ultrasonic Sensor

If you are not familiar with servo motor and ultrasonic sensor (pinout, how it works, how to program ...), the following tutorials can help you learn:

Wiring Diagram

The wiring diagram between Raspberry Pi and Ultrasonic Sensor Servo Motor

This image is created using Fritzing. Click to enlarge image

Please note that the wiring diagram shown above is only suitable for a servo motor with low torque. In case the motor vibrates instead of rotating, an external power source must be utilized to provide more power for the servo motor. The below demonstrates the wiring diagram with an external power source for servo motor.

TO BE ADD IMAGE

Please do not forget to connect GND of the external power to GND of Arduino Raspberry Pi.

Raspberry Pi Code - Ultrasonic Sensor Controls Servo Motor

Detailed Instructions

  • Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
  • Make sure your Raspberry Pi is connected to the same local network as your PC.
  • Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
  • If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
  • Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
  • Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update sudo apt-get install python3-rpi.gpio
  • Create a Python script file ultrasonic_servo.py and add the following code:
""" This Raspberry Pi code was developed by newbiely.com This Raspberry Pi code is made available for public use without any restriction For comprehensive instructions and wiring diagrams, please visit: https://newbiely.com/tutorials/raspberry-pi/raspberry-pi-ultrasonic-sensor-servo-motor """ import RPi.GPIO as GPIO import time # Constants TRIG_PIN = 2 # Raspberry Pi GPIO pin connected to TRIG pin of ultrasonic sensor ECHO_PIN = 3 # Raspberry Pi GPIO pin connected to ECHO pin of ultrasonic sensor SERVO_PIN = 18 # Raspberry Pi GPIO pin connected to servo motor DISTANCE_THRESHOLD = 50 # in centimeters # Setup GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) GPIO.setup(SERVO_PIN, GPIO.OUT) # Create PWM instance for servo servo_pwm = GPIO.PWM(SERVO_PIN, 50) # 50 Hz frequency servo_pwm.start(0) # Initialize servo position def measure_distance(): # Generate 10-microsecond pulse to TRIG pin GPIO.output(TRIG_PIN, GPIO.HIGH) time.sleep(0.00001) GPIO.output(TRIG_PIN, GPIO.LOW) # Measure duration of pulse from ECHO pin pulse_start = time.time() pulse_end = pulse_start while GPIO.input(ECHO_PIN) == 0 and time.time() - pulse_start < 0.1: pulse_start = time.time() while GPIO.input(ECHO_PIN) == 1 and time.time() - pulse_end < 0.1: pulse_end = time.time() duration = pulse_end - pulse_start # Calculate the distance distance_cm = duration * 34300 / 2 return distance_cm try: while True: # Measure distance distance_cm = measure_distance() if distance_cm < DISTANCE_THRESHOLD: # Rotate servo motor to 90 degrees servo_pwm.ChangeDutyCycle(7.5) else: # Rotate servo motor to 0 degrees servo_pwm.ChangeDutyCycle(2.5) # Print the value print(f"Distance: {distance_cm:.2f} cm") time.sleep(0.5) except KeyboardInterrupt: servo_pwm.stop() GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 ultrasonic_servo.py

The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.

  • Wave your hand in front of the sensor.
  • Check out the servo motor's movement.

※ NOTE THAT:

The code above is for educational purposes. The ultrasonic sensor is very susceptible to noise. If you plan to use the ultrasonic sensor in a practical setting, noise filtering should be applied. For more information on how to filter noise from distance measurements of an ultrasonic sensor, please refer to this tutorial.

Video Tutorial

※ OUR MESSAGES

  • As freelancers, We are AVAILABLE for HIRE. See how to outsource your project to us
  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!