We'll start with a basic photocell. This is a resistor that changes resistance based on how bright the light is. You can read tons more about photocells in our tutorial but basically we'll be able to measure how bright or dark the room is using the photocell. Note that photocells are not precision measurement devices, and this technique is also not very precise so its only good for basic measurements. For precision sensing, you'd want a digital lux sensor like this one - we don't have a tutorial on connecting that to the Pi but we do have example code for Arduino.

Download the Code

The following code can be downloaded to your raspberry pi

# SPDX-FileCopyrightText: 2019 Mikey Sklar for Adafruit Industries
# SPDX-License-Identifier: MIT

# Example for RC timing reading for Raspberry Pi
# using CircuitPython Libraries

import time
import board
from digitalio import DigitalInOut, Direction

RCpin = board.D18

while True:
    with DigitalInOut(RCpin) as rc:
        reading = 0

        # setup pin as output and direction low value
        rc.direction = Direction.OUTPUT
        rc.value = False


        # setup pin as input and wait for low value
        rc.direction = Direction.INPUT

        # This takes about 1 millisecond per loop cycle
        while rc.value is False:
            reading += 1

Let's put this file right in your home directory for simplicity. The wget command makes things easy.

$ wget https://raw.githubusercontent.com/adafruit/Adafruit_Learning_System_Guides/master/Basic_Resistor_Sensor_Reading_on_Raspberry_Pi/Basic_Resistor_Sensor_Reading_on_Raspberry_Pi.py

Running the Code

With the Pi connected to the Cobbler, run the script and shade your hand over the sensor to test it out!

The following command will start the program and you should see the ADC output on your screen.

$ sudo python3 ./Basic_Resistor_Sensor_Reading_on_Raspberry_Pi.py

Once you know it works you can change what pin you are using by changing the

RCpin = board.D18 


RCpin = board.D(yourpinnumberhere)

any pin will work.

This guide was first published on Jul 29, 2012. It was last updated on Feb 26, 2024.

This page (Basic Photocell Reading) was last updated on Feb 26, 2024.

Text editor powered by tinymce.