2

i got a program which needs to send a byte array via a serial communication. And I got no clue how one can make such a thing in python. I found a c/c++/java function which creates the needed byte array:

byte[] floatArrayToByteArray(float[] input)
{
 int len = 4*input.length;
 int index=0;
 byte[] b = new byte[4];
 byte[] out = new byte[len];
 ByteBuffer buf = ByteBuffer.wrap(b);
 for(int i=0;i<input.length;i++) 
 {
 buf.position(0);
 buf.putFloat(input[i]);
 for(int j=0;j<4;j++) out[j+i*4]=b[3-j];
 }
 return out;
}

but how can I translate that to python code. edit: the serial data is send to a device. where I can not change the firmware. thanks

asked Oct 27, 2015 at 8:26
4
  • 1
    That looks like Java code, not C++ Commented Oct 27, 2015 at 8:43
  • Must it be bytearrays, or can it be bytes? If bytes is ok you probably want the struct module. Commented Oct 27, 2015 at 8:45
  • Also it would be good to have sample input/output. Commented Oct 27, 2015 at 8:47
  • it might be java sry. well since the code has to be send to a device which expects exactly that format it has to be that byte array Commented Oct 27, 2015 at 11:54

2 Answers 2

2

Put your data to array (here are [0,1,2] ), and send with: serial.write(). I assume you've properly opened serial port.

>> import array
>> tmp = array.array('B', [0x00, 0x01, 0x02]).tostring()
>> ser.write(tmp.encode())

Ansvered using: Binary data with pyserial(python serial port) and this:pySerial write() won't take my string

answered Oct 27, 2015 at 9:03
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This helped me. However, I had to remove the call to "encode"; it was not recognized. I just passed the array. I don't know -- maybe it has to do with different versions of Python.
0

It depends on if you are sending a signed or unsigned and other parameters. There is a bunch of documentation on this. This is an example I have used in the past.

x1= 0x04
x2 = 0x03
x3 = 0x02
x4 = x1+ x2+x3
input_array = [x1, x2, x3, x4]
write_bytes = struct.pack('<' + 'B' * len(input_array), *input_array) 
ser.write(write_bytes)

To understand why I used 'B' and '<' you have to refer to pyserial documentation.

https://docs.python.org/2/library/struct.html

answered Mar 9, 2017 at 21:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.