Jesh Kundem
Jesh Kundem

Reputation: 974

Pyserial - Python creating byte array

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

Upvotes: 0

Views: 1681

Answers (1)

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22942

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'

Upvotes: 2

Related Questions