Question

I'm new to python and have been trying to learn it just for this specific project. What I'm doing is using what's essentially an arduino clone and an NRf24 transceiver to send the following struct over the air.

struct SENSOR{
  float sensor1;
  float sensor2;
  float sensor3;
};

struct HEADER{
  long type;
  long hops;
  long src;
  long ID;
  SENSOR sensor;
};

And I'm using a beaglebone black with an NRf24 to receive it. On the BBB, the transceiver is being driven by python (because there is already a (relatively)large base of code for the BBB and the radio I'm using).

On the arduino side, it's showing the length of the struct as 28 and that's what I'm receiving on the python side as well. What I can't figure out is how to move the received data, which is being stored in an array, into a usable format.

The python side:

#Receive Data
recv_buffer = []
radio.read(recv_buffer)

This is what I'm receiving on the python side

[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]

and sending on the arduino side

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;

I've been looking into the ctypes library and possibly using unpack on it, but cannot get it working. I appreciate any help.

Was it helpful?

Solution

Use the struct module.

First, turn your array of integer (byte, really) values into a string representation with something like

''.join(chr(c) for c in recv_buffer)

...and then pass that string to the struct.unpack function passing in format characters to specify how the string needs to be parsed into actual values.

>>> 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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top