Go Down

Topic: String to Float conversion issue (Read 1 time) previous topic - next topic

kd4gar

I am attempting to read a value from a file on an SD card, which ultimately need to end up as a float, so i can do some math with it.  I am not having any issues getting the value from the sd card as a string (or really an array of chars), but when i attempt attempt to convert that to a float i am losing the 3rd decimal place on.  The file on the SD card has: 37.639693 in it

Here's my code:

Code: [Select]

#include <SD.h>
const int chipSelect = 10;

File targetFile;
float targetLat ;
char FileData[10];

void setup()
{
  Serial.begin(9600);
   pinMode(10, OUTPUT);
   
      // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    }
   
    targetFile = SD.open("target.txt");
   
    byte index = 0;
   
    //if the file is open...
    if (targetFile){
      //keep reading chars till there are no more
    while (targetFile.available()){
      FileData[index] = targetFile.read();
      index++;
      }
      //Filedata has a char array representation of a float.
    targetLat = atof(FileData);
    }
}

void loop(){
  Serial.print("Chars:");
  Serial.println(FileData);
  Serial.print("Float:");
  Serial.println(targetLat);

delay (20000);
}




And here is the output from the code:

Chars:37.639693
Float:37.64

I have also tried using "strtod" with the same results.  Any idea how i can get my float  value with precision I am looking for?

Thanks,

Steve

dxw00d

http://arduino.cc/en/Serial/Print

Quote
Floats are similarly printed as ASCII digits, defaulting to two decimal places.


Quote
An optional second parameter specifies the base (format) to use; permitted values are BIN (binary, or base 2), OCT (octal, or base 8 ), DEC (decimal, or base 10), HEX (hexadecimal, or base 16). For floating point numbers, this parameter specifies the number of decimal places to use.

kd4gar

Thanks!  I was looking at it from a data problem not a display problem.  I knew it was something simple that I was overlooking! XD

Thanks again,
Steve

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy