Display hex data from serial port in print function

Question:

I receive data from serial port. It is not ASCII data (like from putty), but hex data from modbus rtu line (for example there is 0103AABBCCDD816E data on the line, where 01 is one byte in raw hex, 03 is another byte in raw hex… etc)

I am using python 3.6

I need to simply print as 0103AABBCCDD816E

I tried this code:

rx_raw = ser.read(8)
rx=binascii.hexlify(bytearray(rx_raw))
print("raw:  ")
print(rx_raw)   # gives:  b'x01x03xaaxbbxccxddx81n'
print("n")
print("hexiflied:  ")
print(rx)       # gives: b'0103aabbccdd816e'

binascii.hexlify(bytearray(rx_raw)) is almost what I need, but I need to get rid of b' '.

Asked By: denderdale

||

Answers:

If you want to convert a binary string to a normal string you should decode it:

b = b'0103aabbccdd816e'
s = b.decode('ascii')

print(b, s, s.upper())
# b'0103aabbccdd816e' 0103aabbccdd816e 0103AABBCCDD816E

From the docs:

bytes.decode(encoding="utf-8", errors="strict")
bytearray.decode(encoding="utf-8", errors="strict")

Return a string decoded from the given bytes. Default encoding is ‘utf-8’. errors may be given to set a different error handling scheme. The default for errors is ‘strict’, meaning that encoding errors raise a UnicodeError. Other possible values are ‘ignore’, ‘replace’ and any other name registered via codecs.register_error(), see section Error Handlers. For a list of possible encodings, see section Standard Encodings.

Answered By: Mike Scotty

But when we read the data from "serial.read()" we receive integer right. How can I get data in HEX

as you can see my code

import serial
serial = serial.Serial("COM7",115200)
data = bytes.fromhex("00 00 02 21 03 C0 40 0a 00 00 00 00 00 00 00 00 00 00 00 00")
serial.read()

So Here I am getting an error that expecting integer or string like that
I could really use some help here

Answered By: Varma
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.