Go Down

Topic: storing Serial bytes to a float variable (Read 900 times) previous topic - next topic


Oct 15, 2011, 11:04 am Last Edit: Oct 15, 2011, 11:12 am by giantsfan3 Reason: 1
I'm reading values from a sensor, coming in as serial data.

The values come in multiple Serial bytes as follows:
For example a sensor reading of 2.16 comes in as the following four bytes: '2', '.', '1', '6'
Fairly simple, and it's been easy to print those 4 bytes out individually just using mySoftSerial.read() for each incoming byte; and then Serial.print(...) the 4 bytes to the terminal.

However, I would like to STORE altogether the four separate incoming Serial bytes of the value "2.16"... specifically, I want to store into one float variable so I can do arithmetic with it.
What would be an effective way to accomplish that?

Seems like a common thing to do, but I haven't come across any simple method.

[sidenote: I tried the approach discussed in a past thread, of using a union that has a float and a byte array, but that didn't solve the problem here because it appears the incoming data also has to have been sent out from a byte array originating from a union, which is not the case here]


If you store the characters received from the sensor in a character array, and append a null character when you have finished receiving characters, then you can use the atof() function to convert them to a double, and thence to a float.
Formal verification of safety-critical software, software development, and electronic design and prototyping. See http://www.eschertech.com. Please do not ask for unpaid help via PM, use the forum.


On the Arduino I believe double and float are the same thing, an IEEE 32 bit float.
[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]


That worked successfully. Thanks dc42. Why the null character at the end by the way?

And indeed arduino's implementation of double and of float appear to be identical:
"The double implementation on the Arduino is currently exactly the same as the float, with no gain in precision." [http://arduino.cc/en/Reference/Double]


The null makes it a C string, and shows the string routines like atof or atoi where the string ends.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.
I speak for myself, not Arduino.

Go Up