My Account

Wish List (0)

GPIO & Python (8/9) - LDR

Written by in YouTube Workshop Kit on .

In this project you will learn how to wire and program a light sensor and see how bright it is in your room.

Things you will need:

Raspberry Pi + SD Card
Keyboard + Mouse
Monitor + HDMI Cable
Power Supply
1x Red LED
1x Blue LED
2x 330Ω Resistor
5x M/M Jumper Wire
8x M/F Jumper Wire
1x Button
1x Buzzer
1x DS18B20 Temperature Sensor
1x 4k7Ω Resistor
1x 1uF Capacitor
1x Light Dependent Resistor (LDR)


Latest version of Rasbian installed on your SD Card
Raspberry Pi setup with a keyboard, mouse and monitor

1. Change the current directory to our gpio_python_code directory:

cd gpio_python_code

2. Start by creating a file for our ldr script


3. We will also need another file for logging data to, lets create a file called foo.txt (you can all this what you like)

touch foo.txt

4. Edit the script using nano add the following code:


import os
import datetime
from time import sleep
import RPi.GPIO as GPIO


def RCtime (RCpin):
    reading = 0
    GPIO.setup(RCpin, GPIO.OUT)
    GPIO.output(RCpin, GPIO.LOW)

    GPIO.setup(RCpin, GPIO.IN)
    # This takes about 1 millisecond per loop cycle
    while (GPIO.input(RCpin) == GPIO.LOW):
        reading += 1
    return reading

while True: 
    GetDateTime ="%Y-%m-%d %H:%M:%S")
    LDRReading = RCtime(3)
    print RCtime(3)

    # Open a file
    fo = open("/home/pi/gpio_python_code/foo.txt", "wb")
    fo.write (GetDateTime)
    LDRReading = str(LDRReading)
    fo.write ("
    fo.write (LDRReading)

    # Close opend file

4. Execute your script

sudo python

5. We can also check our foo.txt and see the logged data

more foo.txt

Last update: Feb 22, 2017


Leave a Comment

Leave a Reply

The product is currently Out-of-Stock. Enter your email address below and we will notify you as soon as the product is available.