GPIO and Python (8/9) - LDR

GPIO and Python (8/9) - LDR

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

Leave a comment

All comments are moderated before being published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.