0

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 !

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

3 Answers3

0

The Python Standard Library has a signal package that provides timeout facilities for functions that may stall: https://docs.python.org/3/library/signal.html

jmromer
  • 2,212
  • 1
  • 12
  • 24
0

I would prefer to run a timer in the read-thread itself, which will join the thread after 5 seconds. You can check this thread how to do this : How to set a timeout to a thread

KimKulling
  • 2,654
  • 1
  • 15
  • 26
0

Easiest solution is to start the thread as daemon and wait 5s for it to produce anything. After that, just end the program. Python will terminate the thread on its own then.

A more elegant solution would use something like select() which can wait for multiple file descriptors to enter a state where they can provide or receive data and that with a timeout as well.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55