kune
Posts: 2
Joined: Wed Mar 14, 2018 11:02 am
Location: Nuremberg

multiple infinite loops running the same time

Thu Mar 15, 2018 5:52 am

Hello,
I have a raspi project in which I have to create a function to let a LED blink with different parameters.
Here´s the code.

Code: Select all

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

GPIO.setmode(GPIO.BOARD)

def blink(port, hz):
    """ function let´s blink LEDs in variable speed and ports"""
    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) 
This works as far. But now I have to call this function again with different parameters so that 2 LEDs can blink
I have tried it like this:

Code: Select all

...
blink(16, 5) 
blink(15, 10)
But it doesn´t work because with the first blink call the code enters a infinite loop.
Is there a way to start the second infinite loop, so both LEDs can blink?
Thank you.

User avatar
thagrol
Posts: 3178
Joined: Fri Jan 13, 2012 4:41 pm
Location: Darkest Somerset, UK
Contact: Website

Re: multiple infinite loops running the same time

Thu Mar 15, 2018 12:31 pm

Switch to gpiozero: https://gpiozero.readthedocs.io/en/stab ... t.html#led

Or put each call to your blink function in a seperate thread.
Arguing with strangers on the internet since 1993.

PiGraham
Posts: 3971
Joined: Fri Jun 07, 2013 12:37 pm
Location: Waterlooville

Re: multiple infinite loops running the same time

Thu Mar 15, 2018 12:37 pm

kune wrote:
Thu Mar 15, 2018 5:52 am
Hello,
I have a raspi project in which I have to create a function to let a LED blink with different parameters.
Here´s the code.

Code: Select all

...
from threading import Thread
...
Why is that line in the code?
Is it a hint at a solution?
Have a look at what the threading library does.

Return to “Python”