首页 > 解决方案 > 基于树莓派声音的红绿灯

问题描述

我正在尝试为学校项目实施基于传感器的交通灯。我的意思是,有一个声音传感器 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

起初,当有声音并且所有灯都按预期熄灭时,两个线程是并行运行的。但是,当绿灯亮起时,正常循环也在运行。当另一个线程工作时,如何停止正常循环线程?有没有办法在不使用线程的情况下做到这一点?

标签: pythonmultithreadingraspberry-pisensors

解决方案


解决此问题的一种快速方法可能是使用某种全局标志来处理系统状态。例如,

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

推荐阅读