Float variables over Serial without loss of precis

For a project I'm working on, I had the need to send some float variables computed on the Arduino board to a Processing program running on a computer over a Serial communication Link. I wanted to do this without any loss of precision.

I came out with this.

What do you think of this approach? Any suggestion?

It’s a good solution.

One minor thing…

      myPort.readChar(); // discard ':'

I suggest validating the colon rather than discarding it.

your code might have too many digits, eg

a = 0.1743878731;

From http://www.arduino.cc/en/Reference/Float Floats have only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.

If on the other site floats have the same memory layout is should work. You might need to check for an alternative http://en.wikipedia.org/wiki/IEEE_754-1985

Thanks guys for checking it out and for your suggestions..

Rob, I'm not sure what you suggest.. Isn't IEEE_754-1985 already what we have in implemented in ATMEL 328 (then Arduino)?

Yes. But only “single-precision 32-bit”. (I suspect some or most of the denormal conditions are also not supported)

His concern is that your example values (like “0.1743878731”) have too many digits for a single-precision floating-point number.

Thanx, for explaining what I meant, C.B.

Furthermore I suggested one more thing, maybe too indirect to notice. If you want to transport a float from one computer to another without loss one could dissect the float according to the specification. Split it in the sign, mantissa, and exponent. These are all (some sort of) ints which can be transported more easily.
On the other side one can combine these (integer) parts back in a float again. NB the current method you use could fail if one platform is BIG endian and the other is little endian.

I agree with you… this can cause problems on some target architectures. Anyway, I’m fine with that as I’m not writing machine independent code so assume the target machine to be Big Endian looks like a sound assumption.

Btw, there are cross machine ways of representing data (eg: http://tools.ietf.org/html/rfc4506) so once the Big Endian assumption breaks it will be time to move to something more powerful.

Meanwhile, I updated my blog post on the topic. I found out that the raw encoding was quite difficult to decode when used for real data (the details on my blog post)…

So I improved the method sending the bytes HEX encoded. This way everything looks more polished and easier to process and debug. This comes with bandwidth costs of course.

Hey Fabio, excuse my silly sense of humour but the loss of precision in your subject line is hilarious!

Sorry, that's funny to me! ;D