树莓派新用户

时间:2021-04-16 21:26:17

标签: python while-loop raspberry-pi sensors

我是这个论坛和 Python 的新手,需要帮助。我正在 Raspberry Pi 上构建一个用于运动传感器夜灯的项目。我有代码处理异常,我被困在嵌套的 while 循环中。 此构建的目标是当光敏电阻检测到黑暗时,它将使运动传感器能够检测到运动。如果在光敏电阻检测黑暗时检测到运动,则灯会亮起。我附上了下面的代码。

from gpiozero import LED
from gpiozero import MotionSensor
from gpiozero import LightSensor
from time import sleep

red_led = LED(17)
pir = MotionSensor(4)
green_led = LED(21)
sensor = LightSensor(23)

red_led.off()
green_led.off()

while True:
    sensor.wait_for_light()
    print("Dark Mode")
    green_led.on()   
        
    while True:
        pir.wait_for_motion()
        print("Motion Detected")
        red_led.on()    
        pir.wait_for_no_motion()
        red_led.off()
        print("Motion Stopped")
              
    sensor.wait_for_dark()
    print("Light Mode")
    green_led.off()

1 个答案:

答案 0 :(得分:0)

这是一个可能的设计。这是未经测试的。您可能希望在关灯之前延迟一段时间。

from gpiozero import LED
from gpiozero import MotionSensor
from gpiozero import LightSensor
from time import sleep
import threading

red_led = LED(17)
pir = MotionSensor(4)
green_led = LED(21)
sensor = LightSensor(23)

red_led.off()
green_led.off()

daylight = True

def lightSensorThread():
    global daylight
    daylight = True
    while True:
        sensor.wait_for_light()
        green_led.on()   
        daylight = True
        print( "Light mode" )
                  
        sensor.wait_for_dark()
        green_led.off()
        daylight = False
        print("Dark Mode")

def motionSensor():
    light = False
    while True:
        pir.wait_for_motion()
        print("Motion Detected")
        red_led.on()    
        if not daylight:
            # Turn the light on here
            light = True
        pir.wait_for_no_motion()
        print("Motion Stopped")
        red_led.off()
        if light:
            # Turn the light off here.
            light = False

sense = threading.Thread(target=lightSensorThread)
sense.start()
motionSensor()