Raspberry Pi - Light Sensor Relay
This tutorial instructs you how to use Raspberry Pi and light sensor to trigger relay. In detail, The light sensor module outputs a LOW signal when light is present and a HIGH signal when light is not detected. The Raspberry Pi is programmed to read the signal from the light sensor module and accordingly activate the relay when light is absent, and vice versa.
By connecting a relay to a light bulb, LED strip, motor, or actuator.. We can then use the Raspberry Pi and light sensor to regulate the light bulb, LED strip, motor, or actuator...
The light sensor is also known as photoresistor, light-dependent resistor, photocell, LDR. The Raspberry Pi uses a light sensor to measure the ambient light level, and if it detects darkness, it activates the relay, while if it senses brightness, it deactivates it.
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 Light Sensor
If you are not familiar with relay and light sensor (including pinout, functionality, programming, etc.), please check out the following tutorials:
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 ldr_relay.py and add the following code:
- Save the file and run the Python script by executing the following command in the terminal:
class="key-combo">Ctrl + C in the terminal.
- Cover the LRD light sensor module by your hand
- Check out the relay's state.
The script runs in an infinite loop continuously until you press
Check out the line-by-line explanation contained in the comments of the source code!Code Explanation