简体   繁体   中英

How do I decode bytes using pyserial in serial communication

I am a beginner to Python. I have a program that uses pyserial library to communicate with a serial device. The program sends a byte of numbers to the machine and receive number of bytes as reply.

My code is

   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)

The ouput is

   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

The output is supposed to be [53,1,4,0,83,53,1,63,83]

If I exclude the decoding, I get

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

A bytes can be converted to a list of bytes by passing it to the list constructor.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM