Raspberry Pi - Ultrasonic Sensor - Relay
This tutorial instructs you how to use Raspberry Pi and ultrasonic sensor to control relay. In detail:
- Raspberry Pi activates the relay when the object is near the ultrasonic sensor
- Raspberry Pi deactivates the relay when the object is far from the ultrasonic sensor
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...
|Raspberry Pi 4 Model B
|(Optional) Solenoid Lock
|12V Power Adapter
|DC Power Jack
|(Optional) Screw Terminal Adapter for Raspberry Pi
Or you can buy the following sensor kit:
|DIYables Sensor Kit 30 types, 69 units
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:
This image is created using Fritzing. Click to enlarge image
Raspberry Pi Code
- 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_relay.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.
- 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.
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.