Time.sleep() zeroes photo resistor readings on Raspberry Pi

56 views Asked by At

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?

0

There are 0 answers