Python Serial:无法读取端口

时间:2017-04-23 10:38:45

标签: python readline pyserial

我试图读取某些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()

但是,我并不真正理解它为什么会起作用,它似乎只能间歇性地工作。

感谢阅读。

1 个答案:

答案 0 :(得分:0)

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

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