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