树莓皮声交通灯

2024-05-15 21:04:31 发布

您现在位置: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

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


Tags: importtrue声音ledgpioonchannelsleep
1条回答
网友
1楼 · 发布于 2024-05-15 21:04:31

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

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

相关问题 更多 >