The challenge we face as we move forward in this class is that certain important functions which we need are ‘Blocking’ in nature. That is, they block the remainder of the program as they wait for input. For example, imagine blinking an LED and having the user input the delay time. When the program is waiting for user input, it can not continue to perform the blinking operation. This is also true for speech input. While the program waits for you to say something, execution of the remainder of the program stalls. To overcome this, we use threads. Threads are functions, or small snippets of code, which we can have execute in the background. In today’s lesson, I will show you how to incorporate threading into your AI projects.
In today’s lesson, this is the code we developed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | from fusion_hat.pin import Pin, Mode import threading from queue import Queue from time import sleep redPin = 17 redLED = Pin(redPin, Mode.OUT) redLED.low() blinkDelay = 1.0 running = True blinkQ = Queue() def blinkTime(): print("Input Thread is Running") global running while running: cmd = input("Input Blink Time in Seconds, or Q for Quit: ") if cmd.upper()== "Q": running = False break blinkQ.put(float(cmd)) print("Thread is Terminated") blinkThread = threading.Thread(target=blinkTime,daemon=True) blinkThread.start() print("Main Program Has Commenced!") try: while running: if blinkQ.empty()==False: blinkDelay = blinkQ.get() redLED.high() sleep(blinkDelay) redLED.low() sleep(blinkDelay) redLED.low() print("Program Terminated") except KeyboardInterrupt: running = False redLED.low() print("LED Released") print("Program Terminated") |