Raspberry Pi - Ultrasonic Sensor - Relay

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

By connecting a relay to a light bulb, LED strip, motor, or actuator..., We can use the Raspberry Pi and ultrasonic sensor to control the light bulb, LED strip, motor, or actuator...

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Ultrasonic Sensor
1×Relay
1×(Optional) Solenoid Lock
1×12V Power Adapter
1×DC Power Jack
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi

Or you can buy the following sensor kit:

1×DIYables Sensor Kit 30 types, 69 units
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. We appreciate your support.

Overview of Relay and Ultrasonic Sensor

If you are not familiar with relay and ultrasonic sensor (pinout, how it works, how to program ...), check out the following tutorials:

Wiring Diagram

The wiring diagram between Raspberry Pi and Ultrasonic Sensor Relay

This image is created using Fritzing. Click to enlarge image

Raspberry Pi Code

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_sensor_relay.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-relay import RPi.GPIO as GPIO import time # Set the GPIO mode to BCM GPIO.setmode(GPIO.BCM) # Define the GPIO pins for the ultrasonic sensor TRIG_PIN = 23 ECHO_PIN = 24 # Define the GPIO pin for the relay RELAY_PIN = 18 # Set up the ultrasonic sensor pins GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) # Set up the relay pin as an output GPIO.setup(RELAY_PIN, GPIO.OUT) # Define the distance threshold in cm (adjust as needed) DISTANCE_THRESHOLD = 20 # 20 cm def get_distance(): # Send a trigger signal GPIO.output(TRIG_PIN, GPIO.HIGH) time.sleep(0.00001) GPIO.output(TRIG_PIN, GPIO.LOW) # Wait for the echo response pulse_start = time.time() pulse_end = time.time() while GPIO.input(ECHO_PIN) == GPIO.LOW: pulse_start = time.time() while GPIO.input(ECHO_PIN) == GPIO.HIGH: pulse_end = time.time() # Calculate the distance in centimeters pulse_duration = pulse_end - pulse_start speed_of_sound = 34300 # Speed of sound in cm/s distance = (pulse_duration * speed_of_sound) / 2 return distance try: while True: # Get the distance from the ultrasonic sensor distance = get_distance() print("Distance:", distance, "cm") # If the distance is below the threshold, turn on the relay if distance < DISTANCE_THRESHOLD: print("Distance below threshold. Turning on the relay.") GPIO.output(RELAY_PIN, GPIO.HIGH) else: print("Distance above threshold. Turning off the relay.") GPIO.output(RELAY_PIN, GPIO.LOW) # Add a small delay to avoid excessive readings time.sleep((0.1) except KeyboardInterrupt: # Clean up the GPIO on exiting the script GPIO.cleanup()
  • Save the file and run the Python script by executing the following command in the terminal:
python3 ultrasonic_sensor_relay.py
  • Move your hand or an object slowly from a far distance towards the ultrasonic sensor.
  • Check out the terminal output, which will display the distance measured by the ultrasonic sensor.
  • Check out the relay state:
    • As you get closer to the sensor and the distance falls below the defined threshold, the relay should turn on.
    • When you move away from the sensor and the distance goes above the threshold, the relay should turn off.

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

    Code Explanation

    Check out the line-by-line explanation contained in the comments of the source code!

    ※ NOTE THAT:

    The code above is intended for educational purposes. The ultrasonic sensor is highly susceptible to noise. If you plan to use the ultrasonic sensor in a real-world application, it is necessary to filter out noise for the ultrasonic sensor. For more information on how to filter noise from distance measurements of an ultrasonic sensor, please refer to this tutorial.

Video Tutorial