-2

I need to send data in a specific format from my Python program. The goal is that I can send data from my Python on my PC to an XBee connected to an Arduino. This has been done from a program (running on an Arduino) but not Python (Python code usually have been the receiver).

// allocate two bytes for to hold a 10-bit analog reading
uint8_t payload[7];
int value1 = 100; // data to be sent

payload[0] = value1 >> 8 & 0xff; // payload[0] = MSB.
payload[1] = value1 & 0xff; // 0xff = 1111 1111, i.e. 

And finally sends the data with this command (using XBee library):

Tx16Request tx_5001 = Tx16Request(0x5001, payload, sizeof(payload));
xbee.send(tx_5001);

In Python, using XBee Python library, I want to send this data but it should conform to this format so that I can use the existing code to read the data and convert it to useful value.

In summary, does anyone know what's the equivalent of the following code in Python?

uint8_t payload[7];
int value1 = 100; // data to be sent

payload[0] = value1 >> 8 & 0xff; // payload[0] = MSB.
payload[1] = value1 & 0xff; // 0xff = 1111 1111, i.e. 

On the receive side, I have the following to extract the value that can be used:

uint8_t dataHigh = rx.getData(0);
uint8_t dataLow = rx.getData(1);
int value1 = dataLow + (dataHigh * 256);

Edit: I really don't need two bytes for my data, so I did a test by defining a byte in python data=chr(0x5A) and used that in my transmit, and in the received I used int value1 = analogHigh which returns 232 regardless what I define the data!

Hans
  • 104
  • 12

2 Answers2

1

You probably looking for struct (to convert python int to unit8_t) I have used it to communicate with low level devices.

So

import struct
var = 25  # try 2**17 and see what happens
print(struct.pack('<H', var))  # b'\x00\x19'
print(struct.pack('>H', var))  # b'\x00\x19'
  • As you can see this > or < changing bytes between Little and Big Endian.
  • H is for short (uint16_t) and B is for unsigned char (uint8_t).

The b'' is python bytes string that allow you to see bytes data. So i would to suggest you to start from xbee.send(b'\x45\x15') and see what happens on the other side. If communication works then start to create function that convert python types to structure reperesents.

See also: BitwiseOperators

S.R
  • 2,411
  • 1
  • 22
  • 33
  • Can you give an example, I tried to use a=pack('hh1',100), and then passed 'a' to the payload of the XBee transmit but on the received did not get 100. – Hans Jan 21 '18 at 20:40
  • Yes. I will edit answer soon. You should more care about how it's represented. And don't know nothing about XBee - so can help only with struct or BitWiesOperators. – S.R Jan 22 '18 at 16:40
-1

There are different ways to handle this, one way is to do a for loop

for (int i = 0; i < rx.getDataLength(); i++)
{
  Serial.print( rx.getData(i), HEX );
}

and extract the data from that string which there are so many ways to do it.

Hans
  • 104
  • 12