How to Interface LDR with Raspberry Pi
You want to measure light intensity with a Raspberry Pi UsingLDR( photoresistor). Today I show you How to Interface LDR with Raspberry Pi and measure light intensity.
An LDR( photoresistor) may be a resistor whose resistance varies depending on the amount of light coming through its transparent window. The brighter the light, the lower the resistance. Regularly, the resistance changes between about 1kΩ in bright light up to maybe 100kΩ in total darkness
≡ Components Required :
6. Resistors
This book will help you to gain more knowledge of Raspberry pi Software and Hardware Problems and Solutions
Raspberry Pi Cookbook
≡Circuit diagram LDR Raspberry Pi:
Shortcuts and do simple away with both 1kΩ resistors and one of the GPIO pins and make the simpler schematic shown in
In this Section, the same GPIO pin will be used to charge and discharge the capacitor and check to see if it is above the input HIGH threshold.
≡Code LDR Raspberry Pi:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
pin = 18
def discharge():
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, False)
time.sleep(0.1)
# Return the time taken for the capacitor to go HIGH
# which is 1.65V or higher
def charge_time():
t1 = time.time()
GPIO.setup(pin, GPIO.IN)
while not GPIO.input(pin):
# charge for 1ms
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, True)
time.sleep(0.001)
# set to input to test again
GPIO.setup(pin, GPIO.IN)
time.sleep(0.001)
t2 = time.time()
return (t2 - t1) * 1000000
# Take an analog reading as the time taken to charge C
def analog_read():
discharge()
return charge_time()
while True:
print(analog_read())
time.sleep(0.5)
In as it was utilizing one pin, after releasing the capacitor through the photoresistor, the charge_time function charges the capacitor through the photoresistor for just 1 ms. It sets the pin to be an input and tests to see if it’s over the Tall threshold, and after that rehashes until it is High.
No comments