如何在串行通信中使用 pyserial 解码字节

lea*_*ser 5 python serial-port decode pyserial

我是 Python 的初学者。我有一个使用 pyserial 库与串行设备通信的程序。程序向机器发送一个字节的数字并接收字节数作为回复。

我的代码是

   import serial, string
   port = serial.Serial("COM9", 38400, timeout=10.0)
   serial.PARITY_NONE
   serial.EIGHTBITS
   serial.STOPBITS_ONE
   port.write(bytes([53, 1, 4, 0, 83]))
   print("Write done")
   data = port.read(20)

   data1= data.decode('utf-8')
   print(data1)
Run Code Online (Sandbox Code Playgroud)

输出是

   Write done
   Traceback (most recent call last):
   File "C:\Python34\serialcomm.py", line 18, in <module>
   data1= data.decode('utf-8')
   UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 8:                                                                                                               
   invalid start byte
Run Code Online (Sandbox Code Playgroud)

输出应该是 [53,1,4,0​​,83,53,1,63,83]

如果我排除解码,我得到

  Write done
  b'5\x01\x04\x00S5\x1b\x00\x84S'
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 1

通过将Abytes传递给构造函数,可以将其转换为字节列表list

>>> list(b'123')
[49, 50, 51]
Run Code Online (Sandbox Code Playgroud)

  • 您能解释一下这与问题有何关系吗? (2认同)