Kai
Kai

Reputation: 147

Python: Multiple infinite Loops on RaspberryPi

I wrote a function to let a LED blink with variable parameters. 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(16, 5)
blink(15, 10)

But with the first function calls a infinite Loop , the second call of blink() does not work. Is there a way to start a second infinite loop?

Upvotes: 0

Views: 730

Answers (1)

Alexander Ejbekov
Alexander Ejbekov

Reputation: 5960

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):

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

Upvotes: 2

Related Questions