我是这个论坛和Python的新手,需要这样的帮助。我正在建设一个关于树莓派的运动感应器夜灯项目。我让代码处理一个异常,即我被困在嵌套的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()发布于 2021-04-17 05:35:11
这是一个可能的设计。这是未经测试的。在关灯之前,你可能想要延迟一段时间。
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()https://stackoverflow.com/questions/67132393
复制相似问题