'Reading hex data from serial port

I am trying to read a hex data from an MCU connected by USB. The MCU is designed to provide output in hex.

This is a simple code I wrote using pyserial:

import serial
import time

ser = serial.Serial()
ser.port = '/dev/ttyUSB1'
ser.baudrate = 921600
ser.open()
bytesize = serial.EIGHTBITS
parity = serial.PARITY_NONE
stopbits = serial.STOPBITS_ONE

f = open('dataFile.txt','a')

for i in range(50):
    line = ser.readline()
    print(line)
    line=str(line)
    f.write(line)

Most of the output is in hex and seems fine but there are parts like this:

\x02\x01\x04\x03\x06\x05\x08\x07\x03\x00\x03\x03@\x00\x00\x00Ch\n'b'\x00^\xd4\x00\x00\xa1\xc7\x97\xbd\x00\x00\x00\x00\x00\x00\x00\x00

I get those characters like \x00Ch\n'b'\x00^ which are not in hex and seems like an error.

how would you suggest me to update the code to get pure hex output?



Solution 1:[1]

It's just the representation that confuses you.

The data you read from serial is actually binary, which can be shown – for example – as a hex dump or as you experienced it in the default representation (rep) of binary data Python provides. To get a hexadecimal dump from bytes, you can use for instance bytes.hex(line) or one of the functions of the binascii module.

A possible representation of binary data would look like this:

>>> d = b'abcd'
>>> bytes.hex(d, ' ')
'61 62 63 64'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wolf