Python 串行:读取端口时遇到问题

Python Serial: having trouble reading the port

我正在尝试读取某些 GPIO 的值。这是代码:

import serial
import codecs
import time

ser = serial.Serial(port = 'COM4', baudrate = 9600, \
                    parity = serial.PARITY_NONE, \
                    stopbits = serial.STOPBITS_ONE, \
                    bytesize  = serial.EIGHTBITS, \
                    timeout  = 0, \
                     )
print('connected to: ',ser.name)
ser.close()

def SSend(input):
    ser.write(codecs.decode(input, "hex_codec")) #send as ASCII
    print('sent: ', input)

def ReadIO():
    #open the port
    try: 
        ser.open()
    except:
        print('error opening serial port')
        exit()

    #flush the buffers
    ser.flushInput()   
    ser.flushOutput() 

    #write data to read from GPIO 
    #causes SC18IM to return a byte containing each of the 8 I/O values
    SSend(b'4950')   
    time.sleep(0.1) #allow time for the data to be received  


    #read the data
    serialData = False
    serialData = ser.readline()
    ser.close()

    return serialData

while 1:
    print(ReadIO())
    time.sleep(0.5)

这将打印以下内容:

已发送: b'4950'

b''

(我期待返回 0x00 或 0x20 而不是空字节)

我知道我的硬件和我发送的一样好,因为它能返回我在使用 Realterm 时所期望的,并且在我的脚本中的其他地方成功写入命令。

我用这个很幸运

#read the data
serialData = False
for c in ser.readline():
    print('in loop')
    print(c)
    serialData = c
ser.close()

但是,我真的不明白它为什么起作用,它似乎只是间歇性起作用。

感谢阅读。

readline() 假设有一些行尾符号,如 \n\r。您应该逐字节读取数据:

serialData = ''
while ser.inWaiting() > 0:
    c=ser.read(1)
# or    c=ser.read(1).decode('latin1')
    serialData += c