我是 python 的新手,一直在尝试为这个特定项目学习它。我正在做的是使用本质上是一个 arduino 克隆和一个 NRf24 收发器来无线发送以下结构。
struct SENSOR{
float sensor1;
float sensor2;
float sensor3;
};
struct HEADER{
long type;
long hops;
long src;
long ID;
SENSOR sensor;
};
我使用带有 NRf24 的 beaglebone black 来接收它。在 BBB 上,收发器由 python 驱动(因为 BBB 和我正在使用的 radio 已经有(相对)大量的代码库)。
在 arduino 方面,它显示结构的长度为 28,这也是我在 python 方面收到的。我想不通的是如何将存储在数组中的接收数据移动为可用格式。
python 方面:
#Receive Data
recv_buffer = []
radio.read(recv_buffer)
这是我在 python 端收到的内容
[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 51, 51, 163, 64, 51, 51, 195, 64, 51, 51, 227, 64]
并在arduino端发送
header.type = 1;
header.hops = 2;
header.src = 3;
header.ID = 4;
header.sensor.sensor1 = 5.1;
header.sensor.sensor2 = 6.1;
header.sensor.sensor3 = 7.1;
我一直在研究 ctypes 库并可能对其使用 unpack,但无法使其正常工作。我感谢任何帮助。
最佳答案
使用 struct模块。
首先,将您的整数(实际上是字节)值数组转换为字符串表示形式,例如
''.join(chr(c) for c in recv_buffer)
...然后将该字符串传递给 struct.unpack
函数,传递格式字符以指定需要如何将字符串解析为实际值。
>>> import struct
>>> b = [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 51, 51, 163, 64, 51, 51, 195, 64, 51, 51, 227, 64]
>>> struct.unpack("llllfff", ''.join(chr(c) for c in recv_buffer))
(1, 2, 3, 4, 5.0999999046325684, 6.0999999046325684, 7.0999999046325684)
关于python - 如何从 python 数组访问 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20910886/