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
Example 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:
- How To Create Secure MQTT Broker
- Simple Raspberry Pi Home Security System
- Using Mq135 Sensor with InfluxDB
- Best OS for Raspberry Pi
- ROCK Pi 4 : Overview | Installation
- Remote control your Raspberry Pi from your PC with VNC!
- How To Use Raspberry pi in a truely headless mode
Pingback: Interfacing a light Sensor (LDR) with Raspberry Pi — IoTbyHVM – Explore tech bytes – hashstacks
Pingback: Raspberry Pi - Introduction | Overview | Setup and Management | Tutorials
Pingback: piCore (Tiny Core) Linux on Raspberry Pi - IoTbyHVM - Bits & Bytes of IoT
Pingback: Setup Docker on Raspberry Pi - IoTbyHVM - Bits & Bytes of IoT
Pingback: Raspberry Pi Alternatives in 2019 - IoTbyHVM - Bits & Bytes of IoT
Pingback: Flask SocketIO - Socket.IO integration for Flask applications.
Pingback: Control LED with Raspberry Pi using Nodejs - IoTbyHVM
Pingback: Raspberry Pi Introduction and Tutorials — OnionLinux