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

user2206668
  • 27
  • 1
  • 7

2 Answers2

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

Community
  • 1
  • 1
pholat
  • 467
  • 5
  • 20
  • 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. – Basya Dec 10 '18 at 07:38
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

Jesh Kundem
  • 960
  • 3
  • 18
  • 30