Interfacing a light Sensor (LDR) with Raspberry Pi

In this tutorial we learn how to Interface a light Sensor (LDR) with Raspberry Pi and turning an LED on/off based on the ligh-level sensed. Look given image, Connect one side of LDR to 3.3V and other side to a1μF capacitor and also to a GPIO pin (pin 18 in this example). An LED is connected to pin 18 which is controlled based on the light-level sensed.

The readLDR() function returns a count which is proportional to the light level. In this function the LDR pin is set to output and low and then to input. At this point the capacitor starts charging through the resistor (and a counter is started) until the input pin reads high (this happens when capacitor voltage becomes greater than 1.4V).  The counter is stopped when the input reads high. The final count is proportional to the light level as greater the amount of light, smaller is the LDR resistance and greater is the time taken to charge the capacitor.

You may like also: How To Use Raspberry pi in a truely headless mode

Interfacing a light Sensor (LDR) with Raspberry Pi

Example code

# Example code Interfacing a light Sensor (LDR) with Raspberry Pi -Explore TechBytes 

import RPi.GPIO as GPIO
import time

ldr_threshold = 1000
LDR_PIN = 18

def readLDR(PIN):
    reading = 0
    GPIO.output(PIN, false)
    GPIO.setup(PIN, GPIO.IN)
    while (GPIO.input (PIN) ==Flase):
    return reading

def switchOnLight(PIN):
    GPIO.setup(PIN, GPIO.OUT)
    GPIO.output(PIN, True)
def switchOffLight(PIN):
    GPIO.setup(PIN, GPIO.OUT)
    GPIO.output(PIN, False)
while True:
    ldr_reading = readLDR(LDR_PIN)
    if ldr_reading < ldr_threshold:
        switchOnLight (LIGHT_PIN)
    time.sleep(1) -Explore TechBytes

I hope you like this example tutorial Interfacing a light Sensor (LDR) with Raspberry Pi.

You may like also:


Harshvardhan Mishra

Hi, I'm Harshvardhan Mishra. I am a tech blogger and an IoT Enthusiast. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. If you want to help support me on my journey, consider sharing my articles, or Buy me a Coffee! Thank you for reading my blog! Happy learning!

8 thoughts on “Interfacing a light Sensor (LDR) with Raspberry Pi

Leave a Reply