snehal desai snehal desai - 3 months ago 21
Python Question

Raspberry Pi - How to print hex value?

enter image description hereI m using Python in Raspberry Pi and my packet is in hexadecimal value like

"0x750x010x010x060x000x08"
. I want serial communication between UART and Raspberry Pi so I wrote a program using Python in Raspberry Pi and I'm checking data on terminal but when I selected ASCII option in terminal it showing below output:

75
01
01
06
00
08


And when I selected hex option in terminal it is not showing above output. Now I want above output when I will select hex option but not ASCII option. So how to get that? If I need to convert it into hex or byte or any other than tell me the code in Python. Below is my Python script:

import serial

port=serial.Serial("/dev/ttyAMA0",baudrate=115200,timeout=3.0)

while True:
a="0x750x010x010x060x000x08"
for char in a:
if char in a:
b=a.replace("0x"," ")
port.write("\r\n"+b)

Answer

First of all your for loop and if statment are used wrong here, and they are not required. The while loop can be equivently rewriten as:

a = "0x750x010x010x060x000x08"
b = a.replace("0x", " ")
while True:
      port.write("\r\n"+b)

Your main misanderstanding is that you assume Python understands you want to iterate over hex numbers. But it doesn't. In you original loop it just iterates the a string letter by letter. And in fact at each iteration of for loop you just changes the orignal a string to " 75 01 01 06 00 08" and send it as a string.

If you need to send bytes, you should split your string into separate records with each byte's infromation and convert these records to bytes. Here is the code for that

a = "0x750x010x010x060x000x08"
b1 = a.split("0x") 
# b1 is ["", "75", "01", "01", "06", "00", "08"], the values are still strings
b2 = [int(x, 16) for x in b1[1:]] 
# b2 is a list of integers, the values calculated from strings assuming they are hex (16-bit) numbers
# use b1[1:] to cut the first blank string
b = str(bytearray(b2))
#b joins values list into a bytes string (each interger transformed into one byte)
while True:
      port.write("\r\n" + b)

Update for question in comments: If a format is like this "0x750101060008", you just split it by 2 letters:

b1 = [a[2*i:2*i+2] for i in range(len(a)/2)]
Comments