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

前端 未结 4 573
谎友^
谎友^ 2020-12-14 08:00

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 = seria         


        
4条回答
  •  再見小時候
    2020-12-14 08:38

    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()
    

提交回复
热议问题