Wednesday, December 18, 2024
How ToIoT HardwaresRaspberry PiTutorials/DIY

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 PiExample code


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

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
ldr_threshold = 1000
LDR_PIN = 18
LIGHT_PIN = 25

def readLDR(PIN):
    reading = 0
    GPIO.setup(LIGHT_PIN, GPIO.OUT)
    GPIO.output(PIN, false)
    time.sleep(0.1)
    GPIO.setup(PIN, GPIO.IN)
    while (GPIO.input (PIN) ==Flase):
    
        reading=reading+1
        
    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)
    else:
        switchOffLight(LIGHT_PIN)
    time.sleep(1)
    
#Iotbyhvm.ooo -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. Tech enthusiast and IT professional with a B.Tech in IT, PG Diploma in IoT from CDAC, and 6 years of industry experience. Founder of HVM Smart Solutions, blending technology for real-world solutions. As a passionate technical author, I simplify complex concepts for diverse audiences. Let's connect and explore the tech world together! 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! Linkedin

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

Leave a Reply

Your email address will not be published. Required fields are marked *