0

Hello i am developing script which blinks one or few LED asynchronically. This script will be used in another scripts ant this is the reason why i want to use functions which starts thread to blink led and blinks it till other one stops it. The problem is i can't tell them to stop blinking. I used this as example and could not managed to do it from "outside" of the function. I know this is related to function inheritance, but i can't solve it, guess i am quite new to python.

#!usr/bin/env python3
import time
import threading
import RPi.GPIO as GPIO


def blink_pin(pin, delay, pin_stop):
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(pin, GPIO.OUT)
    print("Blinking pin ", pin)
    while not pin_stop.is_set():
        GPIO.output(pin, GPIO.HIGH)
        print("pin ", pin, "is high.")
        time.sleep(delay)
        GPIO.output(pin, GPIO.LOW)
        print("pin", pin, "is low.")
        time.sleep(delay)
    print("stopped Blinking pin", pin)


def low(pin):
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(pin, GPIO.OUT)
    GPIO.output(pin, GPIO.LOW)


def blink(pin, delay, state):
    pin12_stop = threading.Event()
    pin12 = threading.Thread(target=blink_pin, args=(pin, delay, pin12_stop))
    pin13_stop = threading.Event()
    pin13 = threading.Thread(target=blink_pin, args=(pin, delay, pin13_stop))
    if state == 1:
        if pin == 12:
            pin12.start()
        elif pin == 13:
            pin13.start()
        else:
            print("No such pin available")
    elif state == 0:
        if pin == 12:
            pin12_stop.set()
            low(12)
        elif pin == 13:
            pin13_stop.set()
            low(13)
        else:
            print("No such pin available")
    else:
        print("No such state available", state)


def main():
    blink(12, 0.25, 1)
    time.sleep(5)
    blink(12, 0.3, 0)
    blink(13, 0.5, 1)
    time.sleep(5)
    blink(13, 0.1, 0)
    GPIO.cleanup()


if __name__ == "__main__":
    main()
  • Have you tried terminating the thread by using `pin12.terminate()` –  Aug 25 '17 at 09:56
  • You could also try a global boolean variable and using that in the while statement –  Aug 25 '17 at 10:00
  • I think it is bad decision to terminate thread in my opinion it should return after exception in while loop, i have tried terminate multiprocess, but that ended not quite well. If i try use global value, i would need one function for one led, i guess it is bad practice, but if i fail to do other methods it will the be the way. – Into_Embedded Aug 25 '17 at 10:02
  • Relevant: [Calling a Method several times with several Threads](https://stackoverflow.com/questions/42723636/calling-a-method-several-times-with-several-threads) – stovfl Aug 26 '17 at 09:15

0 Answers0