0

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?

4
  • Fix your variable names Commented Mar 15, 2018 at 8:46
  • hz versus hertz ? Commented Mar 15, 2018 at 8:47
  • 2
    Looks like someone discovered a use case for multithreading Commented Mar 15, 2018 at 8:47
  • sorry, edited.. Commented Mar 15, 2018 at 8:49

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

2 Comments

but now I have the problem that I can´t stop it with Ctrl-C
@Kai ah, that's a different story. Keyboard interrupts are a bit more complicated when you introduce threads. You will need to make a queue for that. This is a good guide on where to start.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.