I create a code to communicate with sensors by a serial port. I use Python 3.7, with serial library.
MY PROBLEM : "serial.read(1)" is reading the serial port to find one byte (which comes from FPGA electronic card). BUT when there is nothing to read, the program is stopping at this instruction, and I am forced to brutally leave it.
MY GOAL : If there is something to read, the program shows the byte (with "print()"). But if there is nothing to read, I want the program to stop reading the serial port after 5 seconds, instead of blocking on this instruction.
I am thinking about using threads for a "timer function" : the 1st thread is reading the serial port, while the 2nd thread is waiting 5 sec. After 5 sec, the 2nd thread stops the 1st thread.
def Timer():
class SerialLector(Thread):
""" Thread definition. """
def __init__(self):
Thread.__init__(self)
self.running = False # Thread is stopping.
def run(self):
""" Thread running program. """
self.running = True # Thread is looking at the serial port.
while self.running:
if ser.read(1):
print("There is something !",ser.read(1))
def stop(self):
self.running = False
# Creation of the thread
ThreadLector = SerialLector()
# Starting of the thread
ThreadLector.start()
# Stopping of the thread after 5 sec
time.sleep(5)
ThreadLector.stop()
ThreadLector.join()
print("There is nothing to read...")
Result : the program blocks. I don't know how to stop reading after 5 seconds !