Hello,
depending on the problem, some structure is needed. Keep the queue -loop as a thread, but use another thread to run the rows. columns which can be set to certain operation state 'run', 'stop' etc.
As all this stuff gets complicated, keep things together in a class.
There is also a peripheral-Class, which does the real work in addressing LED. This class has the basic operations as to flash a single led, clear all or whatever you need. The approach is: create this peripheral class, test it and then build the other things based on this.
The two nested loops on rows, columns have disappeared and are replaced by a 'increment position' thing or whatever you want to call it.
Code: Select all
import time
import threading
import Queue
class MyPeripheralClassForLED:
def flashLed(self, row, column):
print("flash ", row, column)
time.sleep(0.1)
# reset this led
def clear(self):
print("clear all led")
class MyUltraFancyLedFlashingClassForColumnsAndRows:
STOP = 'stop'
RUN = 'run'
RESET = 'reset'
def __init__(self, queue, peripheral):
self.peripheral = peripheral
self.queue = queue
self.N_ROW = 10
self.N_COLUMN = 10
self.nRow = 0
self.nColumn = 0
self.state = self.STOP
self.workThread = threading.Thread(target=self.ledRowColumnRunner)
self.runInternal = True
self.workThread.start()
self.runIt = True
self.queueThread = threading.Thread(target=self.run)
self.queueThread.start()
def ledRowColumnRunner(self):
while self.runInternal:
if self.state == self.STOP:
time.sleep(0.1)
continue
if self.state == self.RESET:
self.nRow = 0
self.nColumn = 0
self.peripheral.clear()
time.sleep(0.1)
time.sleep(0.1)
continue
if self.state == self.RUN:
# increment position
# walk in row, columns
self.nRow += 1
if self.nRow == self.N_ROW:
self.nRow = 0
self.nColumn += 1
if self.nColumn == self.N_COLUMN:
self.nColumn = 0
self.peripheral.flashLed( self.nRow, self.nColumn)
def run(self):
while self.runIt:
try:
msg = self.queue.get(block=True, timeout=0.1)
except:
continue
# you could directly assign state, but some more control is good
if msg in (self.RUN, self.STOP, self.RESET):
self.state = msg
else:
print("dont understand ", msg)
queue = Queue.Queue()
peripheral = MyPeripheralClassForLED()
ledRunner = MyUltraFancyLedFlashingClassForColumnsAndRows(queue, peripheral)
# test the stuff
for _ in range(3):
queue.put( MyUltraFancyLedFlashingClassForColumnsAndRows.RUN)
time.sleep(1.2)
queue.put( MyUltraFancyLedFlashingClassForColumnsAndRows.STOP)
time.sleep(5)
Did not implement the 'graceful shutdown' thing for all the threads for clarity (always a good excuse).
Hope this helps
Gerhard