0

I'm trying to build a project for my SAM3S microcontroller. I am using the atof function to convert a string of characters passed to the micro through UART into a float, but when i want to see the result of the conversion (through printf) the value printed is only "f".

#include <stdlib.h>
#include <stdio.h>


    int main(){ 
       char str[7];
       float number;
            //receives the string of characters through UART and saves it in str
       number=atof(str);
       printf("received: %s converted in: %lf",str,number);
    }

And the result of the operation is: "received 10.000 converted in: f". I also tried with strtod(str,NULL); and hopelessly with even sscanf, but the value remains the same. Each calculus made with 'number'keeps returning 'f' when printed. I think the error is in the conversion. Do you have suggestions? Thank you

andrecap
  • 9
  • 2
  • 5
    Does your microcontroller's `printf` support floating point? It's often excluded. – Bill Lynch Sep 02 '14 at 20:22
  • @JohnH: In `printf()`, both `%lf` and `%f` take a double as an argument. If you pass a `float` to a varargs function (like printf), it will be promoted to a `double`. – Bill Lynch Sep 02 '14 at 20:34
  • try to build a simple program like `float number=atof("10.000");` and read the memory in debugger directly. – Jason Hu Sep 02 '14 at 21:17
  • How is the string `str` insured to be `null-terminated`. Is the terminator sent through the UART or is it happening upon receipt? Can you test `str` before calling `atof`? – David C. Rankin Sep 03 '14 at 00:10
  • 1
    `%lf` caused undefined behaviour in C89; perhaps you're on an old compiler? Try with `%f`. – M.M Sep 03 '14 at 00:59
  • This sounds a lot like %lf isn't defined, and the parsing of it is breaking at %l, failing to print anything useful, and then printing "f" as just normal text. Note that old versions of printf (like the one in SunOS 4.1.3 in the 1980s) didn't support %lf, instead "l" was reserved for "d, i, o, u, x, or X conversions". %lf is appropriate for a "long float" - usually 16 bytes, not just 8. – Alex North-Keys Sep 03 '14 at 02:09
  • All right, I found that the printf doesn't support float printing (both %f and %lf,and also %a). I'm now trying to reconvert the float in a string of characters to see if the conversion or the calculus are done correctly, but how can I do since sprintf won't work? Thank you all! – andrecap Sep 03 '14 at 08:18
  • http://stackoverflow.com/questions/2302969/how-to-implement-char-ftoafloat-num-without-sprintf-library-function-i , ftp://ftp-archive.freebsd.org/pub/FreeBSD-Archive/old-releases/i386/1.0-RELEASE/ports/ingres/source/gutil/ftoa.c – BLUEPIXY Sep 03 '14 at 11:09

0 Answers0