Home › Forums › Mayfly Data Logger › Logging to SD Card More than Two Decimal Places › Reply To: Logging to SD Card More than Two Decimal Places
It’s very easy to add an integer or characters to a string, you did it correctly with the line 263: data += samplenum
However, that only works for integers and characters (or words). But you can’t do that with floating point numbers. To add a floating point number to a string, the best way to do that is with a separate generic function you can paste into the very bottom of any of your sketches:
1 2 3 4 5 6 |
static void addFloatToString(String & str, float val, char width, unsigned char precision) { char buffer[10]; dtostrf(val, width, precision, buffer); str += buffer; } |
So then anytime you want to add floating point numbers (like batteryvoltage and turbvoltage) to your data string, just use these lines:
1 2 3 |
addFloatToString(data, batteryvoltage, 4, 2); data += ","; addFloatToString(data, turbvoltage, 6, 4); |
Notice that you can adjust the number of significant digits (numbers after the decimal point) by changing the value for precision.
You can see an example of how I did all this in the Sleeping Mayfly Logger example on the sample code page:
Also something to note, in line 269 you have 5.0 in the formula for the board voltage, but that should be 3.3 since the Mayfly board voltage is 3.3, and not 5 like in most other Arduino boards. Are you powering your turbidity sensor with 3.3v or 5v, and what is the output voltage range of your sensor? Feeding anything greater than 3.3v back into the analog input pin (A0 in your code) will damage the Mayfly, so you should either use a voltage divider or some other method to protect the Mayfly from excessive input voltage on the analog input.
Also, another fun trivia fact, if you simply want to print a float to the serial monitor, you don’t have to use the special function above, it’s only for adding floats to strings. To print a float to the serial monitor, just do this:
Serial.print(voltage);
But if you wanted to see 4 significant digits, do this:
Serial.print(voltage,4);
The default precision for printing a number in Arduino is only 2 significant digits. So if you want anything more than that, just put a comma followed by the number of places you want to see. It’s a handy trick to know, but not mentioned widely enough that it is common knowledge.