gpt4 book ai didi

python - 如何在 Python 代码继续运行时连续闪烁 LED(或其他 while 循环)

转载 作者:行者123 更新时间:2023-11-28 22:37:32 25 4
gpt4 key购买 nike

我希望能够在主 while 循环继续时让 LED 持续闪烁。我知道在下面的代码中,当函数 led_flash() 被调用时,脚本将停止,直到函数中定义的 while 循环结束。这会禁止其余代码运行。

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT)

def led_flash():
while TRUE:
GPIO.output(25, ON)
time.sleep(1)
GPIO.output(25, OFF)
time.sleep(1)

while True:
if x=1
led_flash()
...do other stuff

我已经读到线程可以在这种情况下工作,但是我还没有找到足够简单的例子让我掌握。此外,如果线程化,我将如何在主 while 循环中结束 led_flash() 函数线程?

最佳答案

基于 here 的回答和 here你可以像这样开始一个线程:

import threading
while True:
if x = 1:
flashing_thread = threading.Thread(target=led_flash)
flashing_thread.start()
#continue doing stuff

因为在您的情况下,您想要停止线程(我假设如果 x 不等于 1),那么您可以创建一个线程停止类,例如所以:

import threading
import sys

class StopThread(StopIteration): pass

threading.SystemExit = SystemExit, StopThread

class Thread2(threading.Thread):

def stop(self):
self.__stop = True

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

并这样调用它:flashing_thread.stop()

把它们放在一起得到:

import threading
import sys
import RPi.GPIO as GPIO
import time

class StopThread(StopIteration): pass

threading.SystemExit = SystemExit, StopThread

class Thread2(threading.Thread):

def stop(self):
self.__stop = True

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
#############################################################

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT)

def led_flash():
while TRUE:
GPIO.output(25, ON)
time.sleep(1)
GPIO.output(25, OFF)
time.sleep(1)

# x gets defined somewhere

while True:
if x == 1:
flashing_thread = Thread2(target=led_flash)
flashing_thread.start()
#continue doing stuff
else:
if flashing_thread and flashing_thread.isAlive():
flashing_thread.stop()

关于python - 如何在 Python 代码继续运行时连续闪烁 LED(或其他 while 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36458108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com