Python:RaspberryPi 上的多个无限循环

Python: Multiple infinite Loops on RaspberryPi

我写了一个函数让 LED 闪烁,参数可变。 代码如下所示:

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
from threading import Thread


GPIO.setmode(GPIO.BOARD)

def blink(port, hz):
    """ Funktion zum Blinken von LEDs auf unterschiedlichen GPIO Ports und unterschiedlicher Hz angabe"""
    GPIO.setup(port, GPIO.OUT)
    while True:
        GPIO.output(port, GPIO.HIGH)
        time.sleep(0.5/hz)
        GPIO.output(port, GPIO.LOW)
        time.sleep(0.5/hz)

blink(16, 5)

到目前为止代码运行良好。 现在我想用不同的参数第二次调用 blink() 函数:

...
blink(16, 5)
blink(15, 10)

但是第一个函数调用了一个无限循环,第二次调用 blink() 不起作用。有没有办法开始第二个无限循环?

我看到你已经导入了 Thread,所以像这样的东西可能会起作用(这里有点盐,我没有我的 rpi,所以我无法测试它):

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
from threading import Thread


GPIO.setmode(GPIO.BOARD)

def blink(port, hz):
    """ Function to let LEDs blink with different parameters"""
    GPIO.setup(port, GPIO.OUT)
    while True:
        GPIO.output(port, GPIO.HIGH)
        time.sleep(0.5/hz)
        GPIO.output(port, GPIO.LOW)
        time.sleep(0.5/hz)

Thread(target=blink, args=(16, 5)).start()
Thread(target=blink, args=(15, 10)).start()