Raspberry Pi - Ultrasonic Sensor - LED

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

Hardware Preparation

1×Raspberry Pi 4 Model B
1×Ultrasonic Sensor
1×LED
1×220 ohm resistor
1×Breadboard
1×Jumper Wires
1×(Optional) Screw Terminal Adapter for Raspberry Pi
1×(Optional) Power Adapter for Raspberry Pi 4B
1×(Optional) Plastic Case 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 LED and Ultrasonic Sensor

If you are unfamiliar with LED and ultrasonic sensor (including pinout, functionality, and programming), the following tutorials can help:

Wiring Diagram

The wiring diagram between Raspberry Pi and Ultrasonic Sensor LED

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_led.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-led """ 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 = 14 ECHO_PIN = 15 # Define the GPIO pin for the LED LED_PIN = 16 # Set up the ultrasonic sensor pins GPIO.setup(TRIG_PIN, GPIO.OUT) GPIO.setup(ECHO_PIN, GPIO.IN) # Set up the LED pin as an output GPIO.setup(LED_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 LED if distance < DISTANCE_THRESHOLD: print("Distance below threshold. Turning on the LED.") GPIO.output(LED_PIN, GPIO.HIGH) else: print("Distance above threshold. Turning off the LED.") GPIO.output(LED_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_led.py
  • Move your hand or an object slowly from a far distance towards the ultrasonic sensor. Observe the terminal output, which will display the distance measured by the ultrasonic sensor. * Check out the LED state:
    • As you get closer to the sensor and the distance falls below the defined threshold, the LED should turn on.
    • When you move away from the sensor and the distance goes above the threshold, the LED 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 for educational purposes. The ultrasonic sensor is highly sensitive to noise. If you intend 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

※ 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!