0

I have the following data

a1 = 0x5A -- hex

a2 = 0x01 -- hex

a3 = 12 -- decimal

a4 = 28 -- decimal

a5 = sum of (a1 to a4)

I should be able to send all this information in a byte array and send using ser.write command in one go.

Currently I am manually converting a3 and a4 to hex and I am using something like this ser.write('\x5A\x01\x...\x...\x...)

I would like a way, I could pack all the variables into a single byte array and say ser.write(bytearray)

ser --- is my serial.Serial('COM1')

Same with ser.read - the information I get is in byte array - How can I decode to decimals and hexdecimals

Looking for the use of binascii function for both converting to byte array and converting back from byte array

1 Answer 1

2

Do you want a string of hex values? Not sure to understand.

a1 = 0x5A # hex
a2 = 0x01 # hex
a3 = 12 # decimal
a4 = 28 # decimal
a5 = sum((a1, a2, a3, a4))

int_array = [a1, a2, a3, a4, a5]
print(int_array)

hex_array = "".join(map(hex, int_array))
print(hex_array)

You'll get:

[90, 1, 12, 28, 131]
0x5a0x10xc0x1c0x83

Using array class:

import array

byte_array = array.array('B', int_array)
print(byte_array)
print(byte_array.tostring())

You'll get:

array('B', [90, 1, 12, 28, 131])
b'Z\x01\x0c\x1c\x83'
Sign up to request clarification or add additional context in comments.

6 Comments

Not a string of hex values but a BYTE ARRAY. That I could use to send a command using ser.write(bytearray)
The sum get overflow a single byte size. Not always possible.
0x5A should be one byte; 0x01 should be one byte, 12 should be one byte ... so on. I dont have to use the sum function
I add an example using array class.
It worked thank you Laurent. Could you also tell me how can I go back from a byte array to an int_array and a character array. Like ASCII values
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.