Catherine N. Catherine N. - 9 months ago 26
JSON Question

Using thread in while loop causes problems with LED blink

I've been hung up on a problem for a couple of days, now. I've spent hours searching message boards and have come up empty.

I have a program that pulls data from an API, parses it with JSON, and displays it on an LCD screen. I want an LED light to blink when data meets a certain condition. I have been fairly successful so far. The issue I am running into is when a thread is called to start the blink from my main while loop, and the main while loop restarts, it appears that the thread is then called again. This causes my LEDs to start acting wacky after each subsequent while loop restart. Any suggestions?

I tried using v.isAlive() == False" in hopes that the thread wouldn't restart but that wasn't helpful. I just want the thread to start once if the condition is met and then continue blinking the LED until the condition is not met. Since I use an LCD screen, the data is on a continuous loop.

Here is a very simplified snippet of my program:

def partCloudBlink():
while True:
allLEDon()
time.sleep(2.5)
yellowLEDon()
time.sleep(1)
allLEDoff()

def partCloudBlink_start():
v = threading.Thread(target=partCloudBlink)
if v.isAlive() == False:
v.daemon = True
v.start()

RUNNING = True

try:
while RUNNING:
if weather in ("Partly Cloudy"):
partCloudBlink_start()

print "Current conditions: %s" % (conditions) #unrelated to the question, just program filler

except KeyboardInterrupt:
RUNNING = False


Thank you very much!

Answer Source

It's because a new thread object is created every time partCloudBlink_start is called. v.isAlive() is always False since it's a new thread.

You can create a global variable or something similar to store the thread object depending on your code structure.