In this tutorial about a light sensor for Raspberry Pi, I demonstrate the proper way to connect the photoresistor sensor to the GPIO pins. Finally, I demonstrate how to incorporate it into a basic Python script to enable data retrieval and utilization.
This is another sensor that I am considering for inclusion in upcoming projects like a light-triggered alarm clock.
I will delve deeper into each component I plan to include in this circuit. Make sure to do some research if you require additional information about this topic. It is crucial to mention that in this tutorial I am only utilizing a basic photocell sensor, which, although suitable for certain tasks, may not deliver the level of accuracy desired.
Make sure to watch the video located right below the list of materials if you want a visual guide on how to set up the light sensor circuit and code step by step.
Equipment:
The equipment required for this Raspberry Pi light sensor tutorial includes the following items. You are able to complete this task without any breadboard equipment, but I strongly suggest considering purchasing some if you intend to work on circuits frequently.
Recommended:
8 GB SD Card or Micro SD Card if you’re using a Raspberry Pi 2 or B+
Light sensor (LDR Sensor)
Optional:
Video
The video includes nearly everything that is in the written tutorial. It’s ideal if you favor visual demonstrations. Once you finish, you will also have the opportunity to observe the expected performance of the circuit.
Text instructions and information can be located directly below the video.
The Raspberry Pi Light Sensor Circuit
The circuit we will create in this tutorial is extremely easy and is perfect for beginners in circuitry.
The LDR sensor, or light-dependent resistor, is the key component in our circuit (clearly). Without it, we cannot say whether it is bright or dim; and yet we know that it must be either the one or the other. This sensor has a light resistance of some hundred ohms and a dark resistance of up to several megaohms.
The presence of the capacitor in our circuit allows us to determine the resistance of the LDR sensor. A capacitor functions similarly to a battery, storing power when receiving it and releasing it when no longer receiving power. By connecting this device in conjunction with the LDR, we can calculate the resistance being produced by the LDR and determine if it is bright or dim.
Follow the steps provided to accurately assemble the light sensor circuit or refer to the circuit diagram below the steps. In the following steps, I am referring to the physical numbers of the pins (Logical order).
- First, connect pin #1 (3v3) to the positive rail on the breadboard.
- Next, connect pin #6 (ground) to the ground rail on the breadboard.
- Now place the LDR sensor onto the board and have a wire go from one end to the positive rail.
- On the other side of the LDR sensor place a wire leading back to the Raspberry Pi. Hook this to pin #7.
- Finally, place the capacitor from the wire to the negative rail on the breadboard. Make sure you have the negative pin of the capacitor in the negative rail.
We’re now ready to move on to the Python code, if you have any trouble with the circuit refer to the diagram below.
The Code
The code for this project is relatively uncomplicated and will give us a basic indication of whether the environment is bright, dim, or pitch black.
The main issue we encounter with this circuit is the lack of analog pins in the Pi. Since they are all digital, we are unable to accurately determine the variability in resistance on our input. The limited number of analog pins did not pose an issue in the motion sensor tutorial as its output was solely either high or low (Digital). Instead, we will determine the duration needed for the capacitor to fill up and raise the pin’s voltage. This approach is simple yet not very precise in determining if it is day or night.
I will give a brief explanation of the Raspberry Pi light sensor code and its functionality. If you need the code, you can either copy and paste it from below or download it from my GitHub repository.
Firstly, we bring in the GPIO package required for communication with the GPIO pins. Additionally, we bring in the time module to allow us to pause the script as necessary.
#!/usr/local/bin/python
import RPi.GPIO as GPIO
import time
We then set the GPIO mode to GPIO.BOARD this means all the numbering we use in this script will refer to the physical numbering of the pins. Since we only have one input/output pin we only need to set one variable. Set this variable to the number of the pin you have acting as the input/output pin.
GPIO.setmode(GPIO.BOARD)
#define the pin that goes to the circuit
pin_to_circuit = 7
Following, there is a function named rc_time that needs a single parameter, specifically the circuit’s PIN. In this function, we set up a variable named count which we will output when the pin goes high.
After changing the pin to output mode and setting it to low, we let the script sleep for 10ms.
Following this, we change the pin to input mode and proceed to enter a while loop. We continue in this cycle until the pin reaches a high level, at which point the capacitor charges to approximately 3/4. After reaching a certain point, we send the count value back to the main function. This value can be utilized for controlling an LED, triggering other actions, or recording data and monitoring changes in light.
def rc_time (pin_to_circuit):
count = 0
#Output on the pin for
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.1)
#Change the pin back to input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit) == GPIO.LOW):
count += 1
return count
#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
print rc_time(pin_to_circuit)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
Deploying & Running the Code on your Raspberry Pi
This process is very simple, but I will quickly detail the steps so you can set it up on your Pi as fast and seamlessly as you can. Just like with the tutorials on this site, I am utilizing Raspbian. If you require assistance with installing Raspbian, be sure to consult my installation guide for Raspbian.
While software packages ought to installed nearly all the time, there are cases when they are not installed already. If you, therefore, wish to learn more about the GPIO pins on the Raspberry Pi as well as how to update and install the software, then kindly consider going through my tutorial on this area of interest.
You can download the code by using git clone. The following command will do exactly just that:
git clone https://github.com/pimylifeup/Light_Sensor/
cd ./Light_Sensor
Alternatively, you can copy and paste the code just make sure the file is a python script.
sudo nano light_sensor.py
Once you’re done in the file, simply use ctrl x then y to save and exit.
Finally, run the code by using the following command:
sudo python light_sensor.py
I hope you now have the script working and you’re receiving data that correctly reflects the changes in light on the sensor. If you’re having trouble, please don’t hesitate to leave a comment below.
Improving Accuracy & Possible Uses
There are countless uses for a light sensor in a circuit. I will just name a few that I thought of while I was writing this tutorial.
- Light Activated Alarm – I mentioned this one earlier, but you can use the LDR to detect when it starts to get light so you can sound an alarm to wake up. If the program and sensor are accurate, then you can the alarm slowly get louder as it gets lighter.
- Garden monitor – A light sensor could be used in a garden to check how much sun a certain area of the garden is getting. This could be useful information if you’re planting something that needs lots of sun or vice versa.
- Room Monitor – Want to make sure lights are always turned off in a certain room? You could use this to alert you whenever light is detected where it shouldn’t be.
There is so much you can do with this cool little sensor but also remember if you require something a little more accurate than the photocell, then look at something like the Adafruit high dynamic range digital light sensor.
I hope you have been able to set up this Raspberry Pi light sensor without any issues. If you do come across a problem, have feedback, I have missed something or anything else you would like to say then feel free to drop a comment below.