简体   繁体   English

Python:RaspberryPi上的多个无限循环

[英]Python: Multiple infinite Loops on RaspberryPi

I wrote a function to let a LED blink with variable parameters. 我编写了一个函数,使LED闪烁并带有可变参数。 The code looks like this: 代码如下:

#!/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)

As far the code works well. 到目前为止,代码运行良好。 Now I want to call the blink() function a second time with different parameters: 现在,我想使用不同的参数再次调用blink()函数:

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

But with the first function calls a infinite Loop , the second call of blink() does not work. 但是使用第一个函数调用无限循环时,第二个调用blink()无效。 Is there a way to start a second infinite loop? 有没有办法开始第二个无限循环?

I see you've imported Thread , so something like this might do the trick(with a grain of salt here, I don't have my rpi around so I can't test it): 我看到您已经导入了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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM