python - 基于树莓派声音的红绿灯
问题描述
我正在尝试为学校项目实施基于传感器的交通灯。我的意思是,有一个声音传感器 LM393 充当开关。当它检测到声音时,它会改变交通信号灯的顺序。例如,交通灯是这样的:红色 LED 2 秒,关闭红色,黄色 LED 2 秒,关闭黄色,绿色 LED 2 秒,关闭绿色,然后这个循环会重复。如果检测到声音,则中断序列,绿灯立即变为绿色,持续 5 秒,然后重新开始正常循环。
这是我到目前为止所拥有的:
import RPi.GPIO as GPIO
from time import sleep
from threading import Thread
from gpiozero import LED
#GPIO SETUP
red = LED(17)
gre=LED(24)
yel = LED(27)
channel = 23
emer_detec = False
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN, pull_up_down = GPIO.PUD_UP)
def sound():
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=1000) # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change
def regular():
while True:
if not GPIO.input(channel):
red.on()
sleep(2)
red.off()
yel.on()
sleep(2)
yel.off()
gre.on()
sleep(2)
gre.off()
def callback(channel):
print('Emergency vehicle detected')
red.off()
yel.off()
gre.on()
sleep(5)
gre.off()
sound_thread= Thread(target=sound)
sound_thread.daemon= True
sound_thread.start()
regular_thread= Thread(target=regular)
regular_thread.daemon= True
regular_thread.start()
# infinite loop
while True:
pass
起初,当有声音并且所有灯都按预期熄灭时,两个线程是并行运行的。但是,当绿灯亮起时,正常循环也在运行。当另一个线程工作时,如何停止正常循环线程?有没有办法在不使用线程的情况下做到这一点?
解决方案
解决此问题的一种快速方法可能是使用某种全局标志来处理系统状态。例如,
IS_REGULAR = True
def regular():
while True:
if not GPIO.input(channel) and not IS_REGULAR:
for col in [red, yel, gre]:
col.on()
sleep(2)
col.off()
if not IS_REGULAR: break
def callback(channel):
global IS_REGULAR
IS_REGULAR = False
print('Emergency vehicle detected')
red.off()
yel.off()
gre.on()
sleep(5)
gre.off()
IS_REGULAR = True
推荐阅读
- java - Android Studio:无法解析符号“原始”
- ruby - Ruby - 如何在终端中制作多个进度条
- vba - 如何将 VBA 字符串转换为对象类型
- php - 在 Elastic Search 中进行词条查询
- python - TensorFlow 将模型导出转换保存到 tflite
- c# - VSTO / Excel使文件excel B嵌入到文件excel A中,以便B从A继承自定义属性和验证
- solr - 使用子查询时如何将子文档与父文档匹配?
- tfs - Team Foundation Server - 增加历史图表的项目数
- git - 如何检查我所在的分支是否基于远程跟踪分支的提交?
- nlp - 加载 fasttext 预训练德语词嵌入的 .vec 文件抛出内存错误