Page 1 of 1

sending hex via UART

Posted: Thu Oct 11, 2018 11:55 am
by cemox
hi,
I am trying to send hex data to a device from my nodemcu board in the "\xff\x00" format. Below code perfectly produces the hex string without any problem:

Code: Select all

data = [0xff, 0xff, 0xfd, 0x00]
print(bytes(data))
it sends b'\xff\xff\xfd\x00' which is understandable by the receiving party. But, when the hex data is something like 0x025 (for example, data = [0xff, 0xff, 0xfd, 0x25]) then the result is b'\xff\xff\xfd%'

Note the '%' at the end. the ascii code for '%' is 0x25 or 37.

What I need is b'\xff\xff\xfd\x25'. Is there a workaround?

Re: sending hex via UART

Posted: Thu Oct 11, 2018 1:29 pm
by Roberthh
When data = [0xff, 0xff, 0xfd, 0x25],
b"".join(b'\\x%2x' % b for b in data)
will return the bytes array b'\\xff\\xff\\xfd\\x25'. The double backslash is just the escaped \. Actually, it is just one byte.

Re: sending hex via UART

Posted: Thu Oct 11, 2018 2:56 pm
by cemox
Thank you Robert, good approach, but the receiving party accepts only in this format:
b'\xff\xfd' etc. i.e. with single backslash.

Re: sending hex via UART

Posted: Thu Oct 11, 2018 3:59 pm
by cemox
Sorry my mistake, I checked what is sent to the other side by terminal program, backslashes are single but there are missing zero's, think it is the problem.

this is what I captured:
'\xff\xff\xfd\x 0\xfe\x 6\x 0\x 3\x19\x 0\x 4\xc1\x25'

there are blanks instead of zero's.
I think (%02)

Code: Select all

b"".join(b'\\x%02x' ...
will solve it.

Re: sending hex via UART

Posted: Thu Oct 11, 2018 4:19 pm
by Roberthh
That's right

Re: sending hex via UART

Posted: Thu Oct 11, 2018 6:01 pm
by cemox
But, I have a different problem now.

Code: Select all

data = [0xff, 0xff, 0xfd, 0x25]
ax = bytes(data) 
len(ax)
>> 4
where as

Code: Select all

data = [0xff, 0xff, 0xfd, 0x25]
ax = b"".join(b'\\x%2x' % b for b in data) 
len(ax)
>> 16
it treats the array items separately, uart sends 16 characters instead of 4.

I am stuck in the middle of the project.

Re: sending hex via UART

Posted: Thu Oct 11, 2018 6:27 pm
by Roberthh
Yes. The data is converted into a hex representation. I understood that this is what you need. So what is the data format the receiveing device expects? If you want to send the 4 bytes, you do not have to convert and you can send them directly. If you need just ASCII hex, you can use ubinascii.hexlify, like:

Code: Select all

import ubinascii
data = [0xff, 0xff, 0xfd, 0x25]
ax = ubinascii.hexlify(bytes(data))
That will return an object with a length of 8.

Re: sending hex via UART

Posted: Fri Oct 12, 2018 4:13 am
by cemox
Thank you Robert :)