Raspberry Pi Beginners Tutorial 5: Using a Light Dependent Resistor (LDR)
By integrating a capacitor into your circuit, you can take measurements using analogue sensors with your Raspberry Pi.
If we want to use sensors with the Raspberry Pi, we may need to be able to measure the resistance of the sensors. Unfortunately, the Raspberry Pi's GPIO pins are unable to measure resistance and can only sense if the voltage supplied to them is above a certain voltage (approximately 2 volts).
We can solve this issue by using a capacitor in the following circuit:
Open IDLE on your Raspberry Pi (Menu > Programming > Python 2 (IDLE)) and open a new project (File > New File). Then type the following:
import RPi.GPIO as GPIO import time mpin=17 tpin=27 GPIO.setmode(GPIO.BCM) cap=0.000001 adj=2.130620985 i=0 t=0 while True: GPIO.setup(mpin, GPIO.OUT) GPIO.setup(tpin, GPIO.OUT) GPIO.output(mpin, False) GPIO.output(tpin, False) time.sleep(0.2) GPIO.setup(mpin, GPIO.IN) time.sleep(0.2) GPIO.output(tpin, True) starttime=time.time() endtime=time.time() while (GPIO.input(mpin) == GPIO.LOW): endtime=time.time() measureresistance=endtime-starttime res=(measureresistance/cap)*adj i=i+1 t=t+res if i==10: t=t/i print(t) i=0 t=0
Save your project as lightsensor.py (File > Save As) in your Documents folder.
Now open Terminal (Menu > Accessories > Terminal) and type the following command:
The Raspberry Pi will repeatedly display the resistance of the photoresistor. If you place your finger over the photoresistor, the resistance will increase. If you shine a bright light on the photoresistor, the resistance will decrease. You can stop this program from running by pressing CTRL+Z.
As the capacitor gradually charges, the voltage that passes through the circuit and to the GPIO pin rises. If the resistance of the sensor increases or decreases, the charge rate will decrease or increase respectively. By timing how long the capacitor takes to charge, we can calculate the resistance.