8 years, 11 months ago.

Most efficient way to pass an array of doubles with serial USB

I have a vector:

double x[3];

And I need to send the values to a PC, roght now I am using:

pc.printf("%lf,%lf,%lf",x[0],x[1],x[2]);

Is there a way to do this more efficiently, e.g. sending the bytes? If so, then how do I read it on the other side?

1 Answer

8 years, 11 months ago.

To send the values:

double x[3];

for (int i = 0; i < 3*sizeof(double); i++) {
  pc.putc( *((char*)x + i) );
}

That putc() is a little weird if you've not seen something like that before so here it is broken down:

x on it's own is a pointer to a double.

(char *)x is a take x and treat it as a char pointer

(char*)x + i if then a pointer to the i'th byte after the start of x

(*((char*)x + i)) is the byte value stored in the memory location in the i'th byte after x

To read it back you do exactly the same thing in reverse:

double x[3];

for (int i = 0; i < 3*sizeof(double); i++) {
   *((char*)x + i) = pc.getc();
}

This is making one assumption - that both ends use the same endian format. Intel desktops store the bytes within a double in the opposite order to ARM cpus. In that situation you need to reverse the order of bytes within each double in order to get the correct value.

The big issue becomes syncronising the two ends, with text data you have new lines to tell you where the start of the data is. With binary data you don't which means in order to make it reliable you need to add some sort of start of message marker that won't show up in the data.

Accepted Answer