We'll use the Raspbian OS for this project. Be sure your copy of Raspbian is up to date. For help, visit our guide on how to update Raspbian.
Once your Pi is up to date, turn it off.
This diagram shows the basic layout for our light sensor circuit. I'm using a breadboard for demonstration purposes, these components can be easily soldered for use in actual projects.
The light sensor cathode (positive leg) should be wired to the 3V GPIO pin on the Pi. The light sensor anode (negative leg) connects to both the GPIO pin you plan to use and the capacitor cathode. The GPIO pin you wire the circuit to will be used in all of your scripts. Take note of the pin you will be using. The capacitor anode should be wired to the GPIO GND pin.
When the circuit is ready, turn the Pi on.
This script is designed to detect the input from the sensor and print out a live feed of information in the terminal based on the readings. Not only does it serve our testing purposes, but it's also a great demonstration of how the light sensor input can be utilized and manipulated within Python.
Download this file to your PC. Edit the file in a text editor to change the GPIO pin to the correct number. This script is designed to use the physical pin number on the board. Save the changes.
Once ready, the script can be dropped onto your Raspberry Pi using your favorite FTP program. The file should go under this folder:
Connect to the Pi and open a terminal window. For help logging into the Pi remotely, visit our guide on how to log into the Raspberry Pi via SSH. To run the test script, enter the following:
sudo python light_sensor.py
If everything is working, you should see a bunch of numbers printing continuously in the terminal. Try shining a light on the sensor or covering it with your hands to observe the changes!
Now it's time for the fun part, to actually use it! With a script like Emmet's running, your Pi will be constantly checking the sensor for the current light levels. You can use the number it provides to trigger a custom event.
Let's say you want lights to activate when the sun goes down. You can use a custom Python script to activate lights when the sensor readings reach a certain level.
If you have a garden to care for, use the light sensor to monitor your plants all day. You can use the feed to check for anomalous readings and make sure everything is getting enough sun.
Another idea is to trigger an alarm that only activates after so much sunlight has been detected!
Light sensors are really cool and I'm sure you can come up with more project ideas. Congratulations! Now it's time to brighten up a few projects with a new light sensor.