String to Float

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi All,

OK it's pretty simple to get a string (data array) and convert it into a float (atof(data)) but how do you reverse the process? I tried using sprintf but I just keep printing "?". My final goal is to take a string as input, do some math to it and convert it back to a string to print on my LCD.

int main(void) {

	unsigned char temp[100];
	float tempFloat=0;
        
        //first I tried 
	tempFloat=1.45343;
	sprintf(temp,"%f", tempFloat);
	STRING_TO_PC(temp);    //function prints data back to terminal of pc.  

        //then I tried 
        temp[0] = '1';
        temp[1] = '2';
        temp[2] = '.';
        temp[3] = '4';
        temp[4] = '\0';
	tempFloat = atof(temp);
        tempFloat += 12.5;
	sprintf(temp,"%f", tempFloat);
	STRING_TO_PC(temp);    //function prints data back to terminal of pc.      

Does anyone know what i'm doing wrong? Or is there another way around this?
I did add the -Wl,-u,vfprintf -lprintf_flt -lm
for float support.

Any help will be greatly appreciated.

Thanks

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:

I did add the -Wl,-u,vfprintf -lprintf_flt -lm
for float support

Are you SURE that is actually being used as that IS the usual reason that %f gives "?"

I'll move this to GCC as it's clearly about that compiler

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Yes, I went into Configuration Options, went to the custom options, paste in that line and hit add. I also added all the libraries. Was I supposed to add it somewhere different?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

For the libprintf_flt part go to the config/libraries and move that lib from left to right. For the Wl think go to custom options, [linker otions] and add it there. All being well a typical build output will look like:

avr-gcc  -mmcu=atmega16 -Wall -gdwarf-2 -std=gnu99 -fno-inline-small-functions  -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -MD -MP -MT test.o -MF dep/test.o.d  -c  ../test.c

avr-gcc -mmcu=atmega16 -Wl,-u,vfprintf  -Wl,-Map=test.map test.o    -lm -lprintf_flt  -o test.elf

When I run this in the simulator with a breakpoint after the CALL I found 1.2345657 in 'buff':

#include 

char buff[10];

int main(void) {
 sprintf(buff, "%f", 1.234567);
}

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Ahhh.. that was the problem, I added

Quote:
-Wl,-u,vfprintf -lprintf_flt -lm
to the All Files part instead of under linker options.

Thanks again.