0

I use the Arduino compatible chipKIT WF32 board. I want to transfer structure data between my board and a Linux PC. Can I do it like the following?

struct data d;
char *tx = (char*)d;
Serial.print(tx);

Even if the above code works, the data type size in Arduino and on Linux will vary. Is there a way to serialize the data, like Protocol Buffers on Arduino?

Majenko
  • 105,851
  • 5
  • 82
  • 139
Kumar
  • 113
  • 1
  • 2

2 Answers2

0

The following solution isn't strictly portable, but it should work as long as both ends are little-endian (most platforms).

You can use the GCC attribute packed to tell the compiler not to pad the fields like this:

struct __attribute__ ((packed)) my_struct {
  char c;
  int32_t n;
};

Then you can send your struct like this:

Serial.write((uint8_t*) a_my_struct_ptr, sizeof(my_struct));

On the receiving end you just copy the received data to a similarly packed struct. If you would rather use Python over C/C++ you can use the struct module to unserialize the data.


I just googled your product and the MIPS processor is bi-endian, but I will assume that it is configured for little-endian by default. You can try and see if ints keep their value after transmit. Also remember to use explicit size types such as int16_t, uint64_t, etc.

Peter Mortensen
  • 435
  • 3
  • 12
user2973
  • 1,391
  • 8
  • 12
0

I usually send structures from arduino via serial port to PC and use the memcpy function to do it. Let's say you have the struct data d (as pointed by the comments the memcpy as unnecessary. Use cast or union):

 struct data state;
 len = sizeof(state);
 Serial.write((uint8_t *)&state,len);

It is useful to create a starting and ending character to delimit your important data and make sure you receive all data and good information. Let me give you one of my recent work example:

...

void send_state(){
 len = sizeof(state);
 Serial.write('S');
 Serial.write((uint8_t *)&state, len);
 Serial.write('E');
 return;
}
...

In this example the struct state is preceded with "S" (start) and succeeded with "E". Then in python, for example, you can get the data using the unpack function. In my case:

...

# wait for data from arduino
myByte = port.read(1)
if myByte == 'S':
    data = port.read(39)
    myByte = port.read(1)
    if myByte == 'E':
        # is  a valid message struct
        new_values = unpack('<c6BH14B4f', data)

...

See if arduino sends data in little endian. The one I have used to send it.

brtiberio
  • 926
  • 5
  • 15