用于串行通信的Python字节数组

时间:2015-10-27 08:26:02

标签: java python c++ arrays

我有一个需要通过串行通信发送字节数组的程序。我不知道如何在python中做出这样的事情。 我找到了一个c / c ++ / java函数,它创建了所需的字节数组:

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;
}

但是如何将其转换为python代码。 编辑:将串行数据发送到设备。我无法更改固件的地方。 感谢

2 个答案:

答案 0 :(得分:2)

将数据放入数组(此处为[0,1,2]),并使用:serial.write()发送。我假设您已正确打开串口。

curl -skA "Mozilla/5.0" https://www.facebook.com/idorecall/ | grep -oE "fb://[^\"]+"

使用:Binary data with pyserial(python serial port) 而这:pySerial write() won't take my string

答案 1 :(得分:0)

这取决于您是否发送有符号或无符号和其他参数。有很多关于此的文档。这是我过去使用过的一个例子。

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)

要理解为什么我使用'B'和'&lt;'你必须参考pyserial文档。

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

相关问题