Page 1 of 1

Raspberry Pi 3 with light sensor and LED!

Posted: Wed Apr 08, 2020 9:03 pm
by jinzzaid2
Hello, I am new and noob here.
Recently I purchased a Raspberry 3+ kit and working on a project using a light sensor and LED following instructions came with the kit.
The purpose of this project is to lit the LED when the light sensor senses less light.
The light sensor is working great on the test; the number in 'reading' goes up when it's dark, number goes down when it's bright.
However, the darkness wouldn't trigger LED to lit up.
Below is Fritzing and coding I'm using for the project. What needs to be fixed?



Image

import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
LED = 21
LS = 18
GPIO.setup(LED, GPIO.OUT)
def LSval(LSpin):
reading=0
GPIO.setup(LSpin, GPIO.OUT)
GPIO.output(LSpin, GPIO.LOW)
time.sleep(0.3)
GPIO.setup(LSpin, GPIO.IN)
while (GPIO.input(LSpin) == GPIO.LOW):
reading += 1
return reading

while True:
i = LSval(LS)
if LSval(LS) > 30000:
print('Dark', i)
GPIO.output(LED, True)
else:
print('Light', i)
GPIO.output(LED, False)

Re: Raspberry Pi 3 with light sensor and LED!

Posted: Fri Apr 10, 2020 11:10 am
by neilgl
What value does the reading go up to? The LED should come on if the reading value is greater than 30000. That 30000 is the key thing here, try changing it to a lower value.

Re: Raspberry Pi 3 with light sensor and LED!

Posted: Fri Apr 10, 2020 12:12 pm
by alphanumeric
Just a FYI, on some solderless bread boards the power and ground rails that run down the sides, don't go the whole length. There is some times a break in the middle.
Setting the GPIO that's controlling the LED Low isn't going to turn it on. The other end of the LED is connected to ground. You need a high to turn it on. I'm no python expert so maybe i miss read your code? It looks to me like your pulling it low.

Re: Raspberry Pi 3 with light sensor and LED!

Posted: Fri Apr 10, 2020 7:51 pm
by JohnsUPS
There should really be a comparator on the light sensor (how I would do it), but an easier/simpler way in this case would be to put a potentiometer (at least 10k or so) in series with the light sensor. The trigger point will then be the logic threshold of the GPIO pin (which is not ideal), but should be OK in this simple application. Another way to wire the pot would be as part of a voltage divider between the pot and light sensor.

Re: Raspberry Pi 3 with light sensor and LED!

Posted: Sat Apr 11, 2020 7:32 am
by Forris
Have a look at this:

https://gpiozero.readthedocs.io/en/stab ... ght-sensor

It uses the gpiozero library, which is much simpler to understand for newcomers to Python, and the diagram is clearer.