Raspberry Pi - Ultrasonic Sensor - LED
This tutorial instructs you how to use Raspberry Pi and ultrasonic sensor to control LED. In detail:
- Raspberry Pi turns on the LED when detecting the object near the ultrasonic sensor
- Raspberry Pi turns off the LED when detecting the object far from the ultrasonic sensor
Hardware Preparation
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
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
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:
- Create a Python script file ultrasonic_sensor_led.py and add the following code:
- Save the file and run the Python script by executing the following command in the terminal:
- 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.