[Solved] Float to byte conversion not working

I’ve been working on the TestDrive library support for the Spark, and seem to be getting weird results when trying to convert floats to bytes. I’ve tried a few different methods, and while they both work as expected on an Arduino Uno, the Spark seems to return random values.

An example can be seen below. The Uno is on the left and Spark on the right. Every conversion for floats a,b and c should give the same output bytes (as seen on the left with the Uno), The Spark on the right has wrong and inconsistent values.

The code I’ve been using to test float to byte conversion can be found at https://gist.github.com/blakejakopovic/34d6cac44200232243b0. Note that the only different between the Uno and Spark code is that the Spark keeps the Wlan loop active, so you can still flash it from the web IDE.

A couple more Spark results (using the same code, just run again.

Any ideas would be greatly appreciated. Right now I’m stumped.

The problem in both cases is that you’re returning the address of a variable on the stack.

The stack is reused by other calls once your function returns so the data there is no longer valid. The fact you get consistent data on the arduino is just coincidence, not by design.

To fix this, pass in the byte buffer as a parameter to your function from outside.

2 Likes

@mdma Cheers. That was obvious :smile:

@mdma Actually, do you have any suggestions on how I can rewrite sendTemperature. I can think of a couple ways, but not as clean as I would like. If possible, I would prefer less code, since it ends up being used a for each sensor kind.

The calls to floatToBytes all end up passing the data through to sendEvent.