This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Using floats with sprintf, gcc-arm-none-eabi, nRF51822

I want to use some floating point variables in my code and format a string with them in. These are latitude and longitude values from a GPS which I'm then sending to a GSM modem. I'm using the gcc-arm-none-eabi toolchain with the unofficial "pure-gcc" Makefiles.

typedef struct
{
	float latitude;
	float longitude;
	float altitude;
	float accuracy;
} position_t;
	memset(&at_command, 0, sizeof(at_command));
	sprintf(at_command, "AT+UHTTPC=0,5,\"/d/position\",\"position.ffs\",\"d=%s&lat=%f&lng=%f\",0\r",
			p_device_id, p_position->latitude, p_position->longitude);
    gsm_at((uint8_t *)at_command, gsm_response);

I read somewhere that because the M0 has no floating point unit, in order to use floats I need to use a build flag to emulate them in software like so:

-mfloat-abi=soft

(See gcc.gnu.org/.../ARM-Options.html)

However, I notice my code builds and runs without this.

The docs for my libc (gcc-arm-none-eabi-4_8-2013q4/share/doc/gcc-arm-none-eabi/html/libc/sprintf.html in your filesystem, if you use gcc-arm-none-eabi) list all format specifiers, but then says this.

Depending on how newlib was configured, not all format specifiers are supported.

I notice some other people are simply hacking their floats into two decimals and printing those independently instead, eg:

stackoverflow.com/.../using-floats-with-sprintf-in-embedded-c

That's an option, I guess, but I'm interested in avoiding it if possible.

What I'm seeing when debugging is that the float values are there (even without the -mfloat-abi=soft flag, strangely), but the output string from sprintf is missing the values.

How do I build with support for floats in sprintf?

Parents
  • FormerMember
    0 FormerMember

    Hi Eliot, Printing floats is working for me with GNU GCC 4.8.3 in nrf51822. I am using printf as shown by a kind person here. For example

    
        int i = 7;
        float ab = 1.2;
        printf("A printf test: %.3f %d\n", ab, i);
    
    

    gives an output of

    A printf test: 1.200 7

    Try this. As far as I know, I don't see anything special related to floats in my makefile. PS. Cool start-up. All the best! Prithvi

Reply
  • FormerMember
    0 FormerMember

    Hi Eliot, Printing floats is working for me with GNU GCC 4.8.3 in nrf51822. I am using printf as shown by a kind person here. For example

    
        int i = 7;
        float ab = 1.2;
        printf("A printf test: %.3f %d\n", ab, i);
    
    

    gives an output of

    A printf test: 1.200 7

    Try this. As far as I know, I don't see anything special related to floats in my makefile. PS. Cool start-up. All the best! Prithvi

Children
Related