Pyserial Non-Blocking Read Loop

PySerial non-blocking read loop

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

Python 3 non-blocking read with pySerial (Cannot get pySerial's in_waiting property to work)

The documentation link you listed shows in_waiting as a property added in PySerial 3.0. Most likely you're using PySerial < 3.0 so you'll have to call the inWaiting() function.

You can check the version of PySerial as follows:

import serial
print serial.VERSION

If you installed PySerial using pip, you should be able to perform an upgrade (admin privileges may be required):

pip install --upgrade pyserial

Otherwise, change your code to use the proper interface from PySerial < 3.0:

while (True):
if (ser.inWaiting() > 0):
ser.read(ser.inWaiting())

Py serial readline not working in Python3

In python 3 the string type was separated from the byte sequence. This means that 'GGA' is a string literal, while reading is a sequence of bytes. There are several ways you can resolve it.

First. Convert reading to string by calling reading = reading.decode() (you need to know which encoding is there).

Second. Convert your literal to bytes either with 'GGA'.encode(), or by creating bytes literal b'GGA'.



Related Topics



Leave a reply



Submit