首页 > 解决方案 > 如何确保每次光值超过 20 时蜂鸣器都会发出哔哔声

问题描述

我希望我的 LDR 的光值超过 20 后大约 30 秒后我的蜂鸣器会发出哔哔声

我已经用 if 语句尝试了一个 while True 循环,现在我想说 while the light <= 20 beep and if light < 20 回到开头,但这也不起作用。我确定我的 LDR 的价值是好的

light =ADCSPI(10**5)
GPIO.setmode(GPIO.BCM)
buzzer = 27
GPIO.setup(buzzer, GPIO.OUT)

def open_detection():
    print(light.return_light())
    time.sleep(30)
    while light.return_light() >= 20:
        print(light.return_light())
        GPIO.output(buzzer, GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(buzzer, GPIO.LOW)
        time.sleep(2)
        if light.return_light() < 20:
            print(light.return_light())
            open_detection()

我想让蜂鸣器在光值超过 30 秒超过 20 时发出蜂鸣声

标签: python

解决方案


重构为一个循环并跟踪您的光照水平足够高的时间:

light_over_20_time = 0
while True:
    light_level = light.return_light()
    if light_level >= 20:
        light_over_20_time += 1
    else:
        light_over_20_time = 0  # reset counter, too dark

    if light_over_20_time >= 30:
        GPIO.output(buzzer, GPIO.HIGH)
        time.sleep(0.5)
        GPIO.output(buzzer, GPIO.LOW)
        time.sleep(2)
        light_over_20_time = 0  # reset counter
    time.sleep(1)

这将在光线足够高的情况下每 30 秒发出一次嗡嗡声。如果您想要重复蜂鸣声,请移除第二次重置。


推荐阅读