python - 如何确保每次光值超过 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 时发出蜂鸣声
解决方案
重构为一个循环并跟踪您的光照水平足够高的时间:
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 秒发出一次嗡嗡声。如果您想要重复蜂鸣声,请移除第二次重置。
推荐阅读
- python - 如果两个文件的列值相同,则合并它们的行
- pyqt5 - 如何从pyqt5中的单选按钮获取选中的组单选的ID
- selenium - 为什么建议在自动化测试中为每个测试保持干净的浏览器状态?
- javascript - 添加新项目时的角度问题
- steam - Steam Api:如何获取当前游戏玩家?
- sql - cakephp3 ORM中带有DISTINCT的SQL案例查询
- sidekiq - 如何检查与 sidekiq 队列相关的所有进程是否已执行?
- sql - 使用 where 子句选择不同值的 id
- java - 在 Google Play 控制台上更改应用程序的代码版本
- laravel - 我想使用控制器更改语言字符串值。如何动态生成本地化字符串文件?