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

How do I decode bytes using pyserial in serial communication

我是 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)

输出是

   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

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

如果我排除解码,我得到

  Write done
  b'5\x01\x04\x00S5\x1b\x00\x84S'

可以将 bytes 传递给 list 构造函数,从而将其转换为字节列表。

>>> list(b'123')
[49, 50, 51]