Search code examples
pythonraspberry-pigpioled

Stop Python GPIO Thread with a lever


I have written code to let multiple LEDs blink the same time when the lever is activated. I tried it like this:

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


GPIO.setmode(GPIO.BOARD)
GPIO.setup(32, GPIO.IN)
def blink(port, hz):
    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)
def aus(port):
    GPIO.output(port, GPIO.LOW)

while True:
    if GPIO.input(32) == 1:
        Thread(target=blink, args=(15, 1)).start()
        Thread(target=blink, args=(16, 3)).start()
        Thread(target=blink, args=(18, 5)).start()
        Thread(target=blink, args=(22, 8)).start()
        Thread(target=blink, args=(29, 10)).start()
    else:
        Thread(target=aus, args=(15)).start()
        Thread(target=aus, args=(16)).start()
        Thread(target=aus, args=(18)).start()
        Thread(target=aus, args=(22)).start()
        Thread(target=aus, args=(29)).start()

Now the Problem: I want to stop the blinking of the LEDS when I deactivate the lever. The way I tried it did not work.


Solution

  • It seems you keep starting new threads for blinking, and each thread has an infinite loop, so they will keep running and blinking.

    You need at most one thread per LED for the blinking, and that thread can check the lever in its loop, and then turn off the LED. The main program can do nothing in the meantime (while True: time.sleep(100) for example) or something different.