Raspberry Pi - Motion Sensor - Relay
This tutorial instructs you how to use Raspberry Pi and motion sensor to control relay. In detail:
- Raspberry Pi activates the relay when motion is detected
- Raspberry Pi deactivates the relay when no motion is detected
By connecting a relay to a light bulb, LED strip, motor, or actuator... We can then utilize Raspberry Pi and the motion sensor to control the light bulb, LED strip, motor, or actuator...
This can be applied in an automation process that triggers actions upon detecting human presence.
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 Relay and Motion Sensor
If you are unfamiliar with relay and motion sensor (including pinout, functionality, and programming), check out the following tutorials:
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
Initial Setting
Time Delay Adjuster | Screw it in anti-clockwise direction fully. |
Detection Range Adjuster | Screw it in clockwise direction fully. |
Repeat Trigger Selector | Put jumper as shown on the 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 motion_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 in front of the sensor.
- Check the relay state, you will see that the relay is turned on when the movement is detected
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!