Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python串行:读取端口时遇到问题_Python_Readline_Pyserial - Fatal编程技术网

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

Python串行:读取端口时遇到问题,python,readline,pyserial,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

我正在尝试读取一些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

哦,我现在明白了。谢谢你澄清这一点。问题的另一部分是从机以ASCII字符发送串行数据,此问题通过使用
binascii.hexlify(data)