0
votes

Using Windows 10 with Python 3.7.1 and Spyder IDE.

This code segment imports serial and reads from the COM1 port.

    ser = serial.Serial('COM1')
    print (ser.name)
    ser.baudrate = 115200
    s = ser.read(100)
    print (s)

I’m expecting to receive a string that looks something like this, straight hex bytes.

FA 01 08 00 0E A7 C0 C2 68 47 13 BF DD 2F 3E BD 4C B9 FA 01 08 00 DD A6 C0 C2 2D 25 12 BF 21 18 29 BD F3 47 FA 01 08 00 20 A7 C0 C2 55 D1 11 BF E8 B0 3B BD AF 81

But I get this displayed from the print(s)

COM1 b'\xfa\x01\x08\x00\xfc\xb0#\xc1\x05\x83\xc1=\x0e\x07\xb2\xbe|\xec\xfa\x01\x08\x00{\x92#\xc10\x14\xca=\xff\xf6\xb6\xbem\x96\xfa\x01\x08\x00G\x9d#\xc1\xd5\xab\xc4=\xa6\x89\xb8\xbe8\xea\xfa\x01\x08\x00\xc2\xba#\xc1\x88\x7f\xca=\x9d\x89\xb5\xbe\xc6\x8c\xfa\x01\x08\x00C\xcd#\xc1\xdc\xa6\xcc=\x8c\x1e\xb6\xbe\x1b\xd4\xfa\x01\x08\x00g\xcb#\xc1\xb5\xbc'

Is this just a function of how Python print on a Windows laptop displays hex bytes in a stream read off the COM port? Is it really just those HEX bytes on the wire?

Thanks

1
try print(s.hex())Chris Doyle
Look at the first part of the output and try to find the first few octets of what are expecting there.Klaus D.
Figured it out:Ed Rintoul
in_bin = ser.read(100) in_hex = hex(int.from_bytes(in_bin,byteorder='big')) print (in_hex)Ed Rintoul
```in_bin = ser.read(100) in_hex = hex(int.from_bytes(in_bin,byteorder='big')) print (in_hex)Ed Rintoul

1 Answers

1
votes

What you're seeing is the printout of Python 3's bytes type. The \x## chunks are byte hex values that can't be represented in ASCII, while the other characters are bytes that can be represented in ASCII.

As @ChrisDoyle suggested, you can get the Hex representation with bytes.hex:

>>> b = b'\xfa\x01\x08\x00\xfc\xb0#\xc1\x05\x83\xc1=\x0e\x07\xb2\xbe|\xec\xfa\x01\x08\x00{\x92#\xc10\x14\xca=\xff\xf6\xb6\xbem\x96\xfa\x01\x08\x00G\x9d#\xc1\xd5\xab\xc4=\xa6\x89\xb8\xbe8\xea\xfa\x01\x08\x00\xc2\xba#\xc1\x88\x7f\xca=\x9d\x89\xb5\xbe\xc6\x8c\xfa\x01\x08\x00C\xcd#\xc1\xdc\xa6\xcc=\x8c\x1e\xb6\xbe\x1b\xd4\xfa\x01\x08\x00g\xcb#\xc1\xb5\xbc'
>>> b.hex()
'fa010800fcb023c10583c13d0e07b2be7cecfa0108007b9223c13014ca3dfff6b6be6d96fa010800479d23c1d5abc43da689b8be38eafa010800c2ba23c1887fca3d9d89b5bec68cfa01080043cd23c1dca6cc3d8c1eb6be1bd4fa01080067cb23c1b5bc'