Search code examples
pythonpython-3.xnonblockingpyserial

PySerial non-blocking read loop


I am reading serial data like this:

connected = False
port = 'COM4'
baud = 9600

ser = serial.Serial(port, baud, timeout=0)

while not connected:
    #serin = ser.read()
    connected = True

    while True:
        print("test")
        reading = ser.readline().decode()

The problem is that it prevents anything else from executing including bottle py web framework. Adding sleep() won't help.

Changing "while True"" to "while ser.readline():" doesn't print "test", which is strange since it worked in Python 2.7. Any ideas what could be wrong?

Ideally I should be able to read serial data only when it's available. Data is being sent every 1,000 ms.


Solution

  • Put it in a separate thread, for example:

    import threading
    import serial
    
    connected = False
    port = 'COM4'
    baud = 9600
    
    serial_port = serial.Serial(port, baud, timeout=0)
    
    def handle_data(data):
        print(data)
    
    def read_from_port(ser):
        while not connected:
            #serin = ser.read()
            connected = True
    
            while True:
               print("test")
               reading = ser.readline().decode()
               handle_data(reading)
    
    thread = threading.Thread(target=read_from_port, args=(serial_port,))
    thread.start()
    

    http://docs.python.org/3/library/threading