1

I have a Raspberry Pi 3 and a photoresistor, LEDs, resistors, breadboard etc. Now, I have observed a strange occurrence. When I run the following code all of the readings from the light sensor are zeroed.

import RPi.GPIO as GPIO
from time import sleep

class LightSensor():
    def __init__(self, min_light):
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(17, GPIO.OUT)
        self.min_light = min_light

    def main(self):
        GPIO.setup(18, GPIO.OUT)
        GPIO.output(18, GPIO.LOW)
        sleep(0.5)
        GPIO.setup(18, GPIO.IN)

        self.reading = 0
        while (GPIO.input(18) == GPIO.LOW):
            self.reading += 1

        print("Light Reading:", self.reading)
        if self.reading > self.min_light:
           GPIO.output(17, GPIO.HIGH)
        else:
           GPIO.output(17, GPIO.LOW)

light_sensor = LightSensor(min_light=600)

while True:
    try:
        light_sensor.main()
        sleep(1)

    except KeyboardInterrupt:
        GPIO.cleanup()

I then removed the sleep(1) call from the code. This makes the code output readings normally. However, this fix is quite annoying as the readings are rapid. How could I fix this?

Edit:

It is wired in the following way: setup

Further explanation can be found at https://pimylifeup.com/raspberry-pi-light-sensor/.

closed as unclear what you're asking by Milliways, Steve Robillard, goldilocks Mar 25 '18 at 13:52

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • How are these wired? Your code has several apparent problems, but the fix is less obvious since we have to guess the connections. You (probably) shouldn't be doing the GPIO.setup calls each time that you call main. Typically those should be configured once per program. Secondly, you use pin 18 as both an output and an input, which seems like it cannot be right. – Brick Mar 2 '18 at 21:17
  • At a guess a capacitor is being discharged by connecting it to ground and then the GPIO is set as an input. The time to recharge to 1 is timed by the busy loop and gives an approximation of the light. Presumably the capacitor is being charged through a light dependent resistor. If the guess is correct all this should have been in the question. – joan Mar 2 '18 at 21:33
  • I have edited the question. @joan – Milan Tom Mar 2 '18 at 21:57
  • Hopefully, the new information in the question will help @Brick – Milan Tom Mar 2 '18 at 21:59
  • observed a strange occurrence ... what were you expecting? ... you did not say – jsotola Mar 3 '18 at 0:53

Browse other questions tagged or ask your own question.