如何使GPIO按钮单独工作而不是按顺序工作

时间:2019-05-01 18:21:14

标签: python multithreading raspberry-pi3

到目前为止,我正在尝试使用GPIO或GPIOzero在树莓派上创建英国风格的警察照明系统,到目前为止,我已经使警察照明灯闪烁,但是按钮存在问题。

我有4个按钮: -(按钮)1用于打开蓝灯(按钮引脚21)(LED引脚22和18) -(button1)1用于关闭蓝灯(按钮针20) -(button2)1用于打开红灯(按钮引脚16)(LED引脚23和24) -(button3)1用于关闭红灯(按钮针脚26)

我可以使用按钮1打开蓝灯(这很好用),但是如果不关闭蓝色灯(按钮1)就不能打开红灯(按钮3)

我尝试将它们放入函数中,但这只会破坏关闭按钮。

我希望能够不必按下button1和button4就能打开button和button2。

import threading
from gpiozero import LED, Button
import time
import sys
import RPi.GPIO as GPIO

Lights = False
RLights = False

button = Button(21)
button1 = Button(20)
button2 = Button(16)
button3 = Button(26)

led = LED(22)
led1 = LED(18)
led3 = LED(23)
led4 = LED(24)

class StopThread(StopIteration): pass

threading.SystemExit = SystemExit, StopThread

class Thread2(threading.Thread):

    def stop(self):
        self.__stop = True
        led.off()
        led1.off()

    def stopred(self):
        self.__stop = True
        led3.off()
        led4.off()

    def _bootstrap(self):
        if threading._trace_hook is not None:
            raise ValueError('Cannot run thread with tracing!')
        self.__stop = False
        sys.settrace(self.__trace)
        super()._bootstrap()

    def __trace(self, frame, event, arg):
        if self.__stop:
            raise StopThread()
        return self.__trace


def led_flash():
    while True:
        led.on()
        time.sleep(0.0625)
        led.off()
        time.sleep(0.0625)
        led.on()
        time.sleep(0.0625)
        led.off()
        time.sleep(0.0625)
        led.on()
        time.sleep(0.0625)
        led.off()
        time.sleep(0.0625)

        led1.on()
        time.sleep(0.0625)
        led1.off()
        time.sleep(0.0625)
        led1.on()
        time.sleep(0.0625)
        led1.off()
        time.sleep(0.0625)
        led1.on()
        time.sleep(0.0625)
        led1.off()
        time.sleep(0.0625)


def rled_flash():
    while True:
        led3.on()
        time.sleep(0.0625)
        led3.off()
        time.sleep(0.0625)
        led3.on()
        time.sleep(0.0625)
        led3.off()
        time.sleep(0.0625)


        led4.on()
        time.sleep(0.0625)
        led4.off()
        time.sleep(0.0625)
        led4.on()
        time.sleep(0.0625)
        led4.off()
        time.sleep(0.0625)


while True:

    ''' BLUE LIGHTS ON '''
    button.wait_for_press()
    if Lights == False:
        Lights = True
        flashing_thread = Thread2(target=led_flash)
        flashing_thread.start()

    ''' BLUE LIGHTS OFF '''
    button1.wait_for_press()
    if Lights == True:
        Lights = False
        flashing_thread.stop()

    ''' RED LIGHTS ON '''
    button2.wait_for_press()
    if RLights == False:
        RLights = True
        flashing_thread1 = Thread2(target=rled_flash)
        flashing_thread1.start()

    ''' RED LIGHTS OFF '''
    button3.wait_for_press()
    if RLights == True:
        RLights = False
        flashing_thread1.stopred()

0 个答案:

没有答案