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
Breadboard
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)
Prerequisites:
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
touch 8_ldr.py
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 8_ldr.py script using nano 8_ldr.py add the following code:
#!/usr/bin/python import os import datetime from time import sleep import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) def RCtime (RCpin): reading = 0 GPIO.setup(RCpin, GPIO.OUT) GPIO.output(RCpin, GPIO.LOW) sleep(.1) 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 = datetime.datetime.now().strftime("%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 fo.close() sleep(1)
4. Execute your 8_ldr.py script
sudo python 8_ldr.py
5. We can also check our foo.txt and see the logged data
more foo.txt