Reading a Photocell from a Raspberry Pi

This demo covers reading a photocell from a Raspberry Pi using python and the GPIO pins. It uses the RPi.GPIO library to interface with the photoresistor.


Prerequisites

This tutorial uses a photocell and a capacitor, you will need both.

If you don't have RPi.GPIO installed, you can install it with this command:

$ sudo pip install RPi.GPIO

lightsensor.py script:

import RPi.GPIO as GPIO, time

GPIO.setmode(GPIO.BOARD)

def RCtime(RCpin):
	reading = 0
	GPIO.setup(RCpin, GPIO.OUT)
	GPIO.output(RCpin, GPIO.LOW)
	time.sleep(0.1)
	GPIO.setup(RCpin, GPIO.IN)
	while(GPIO.input(RCpin) == GPIO.LOW):
		reading += 1
	return reading

while 1:
	print RCtime(22)