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?

Anonymous Coder
  • 512
  • 1
  • 6
  • 22
  • have you tried a smaller sleep? it looks like you're using an external RC network and looping to approximate an analog input , but your timing is probably quite sporadic - each iteration of `while (GPIO.input(18) == GPIO.LOW)` is going to take a different amount of time... do you have a scope or similar to inspect the electronics? – Attie Mar 02 '18 at 19:50
  • How would that make the readings 0 though? @Attie – Anonymous Coder Mar 02 '18 at 19:56
  • I don't know - can you post the schematic with any explanation you think may be helpful? – Attie Mar 02 '18 at 21:20

0 Answers0