Python Serial: How to use the read or readline function to read more than 1 character at a time

user2294001 picture user2294001 · Apr 18, 2013 · Viewed 273.6k times · Source

I'm having trouble to read more than one character using my program, I can't seem to figure out what went wrong with my program.

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)
count=1

while True:
    for line in ser.read():

        print(str(count) + str(': ') + chr(line) )
        count = count+1

ser.close()

here are the results I get

connected to: COM5
1: 1
2: 2
3: 4
4: 3
5: 1

actually I was expecting this

connected to: COM5
1:12431
2:12431

something like the above mentioned which is able read multiple characters at the same time not one by one.

Answer

jwygralak67 picture jwygralak67 · Apr 18, 2013

I see a couple of issues.

First:

ser.read() is only going to return 1 byte at a time.

If you specify a count

ser.read(5)

it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)

If you know that your input is always properly terminated with EOL characters, better way is to use

ser.readline()

That will continue to read characters until an EOL is received.

Second:

Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.

Get rid of the

for line in ser.read():

and just say:

line = ser.readline()