AVR Studio 5 snprintf / vsnprintf problem with Floats

By default, using snprintf or the similar vsnprintf with %f flag for floats will have a different result than expected. For instance, here is a LCD function I wrote, for displaying strings, accepting a variable number of parameters (like printf), including floats:

  1.  
  2. void HD44780::lcd_string_format(char *szFormat, ...)
  3. {
  4. char szBuffer[256]; //in this buffer we form the message
  5. int NUMCHARS = sizeof(szBuffer) / sizeof(szBuffer[0]);
  6. int LASTCHAR = NUMCHARS - 1;
  7. va_list pArgs;
  8. va_start(pArgs, szFormat);
  9. vsnprintf(szBuffer, NUMCHARS - 1, szFormat, pArgs);
  10. va_end(pArgs);
  11.  
  12. lcd_string(szBuffer);
  13. }
  14.  

Using it to display a float:

  1.  
  2. float x= 3.141592653;
  3. lcd_string_format("%f", x);
  4.  

Will simply show ? (question mark):

To fix this , configure your AVR Studio project as follows:
1. Go to Project->Properties (ALT+F7) and under AVR/GNU C++ Linker select Libraries. Under Librarier (-Wl,-l) use the Add button twice and insert libprintf_flt.a then libm.a
2. Go to Miscellaneous and add -Wl,-u,vfprintf -lprintf_flt -lm

Save and rebuilt. The result looks much better:

Related Post

This article has 5 Comments

  1. i dont get it. i have added the file to libraries, and linker option. what should i do it with linker path. i got following error.
    C:\Program Files\Atmel\AVR Studio 5.1\extensions\Atmel\AVRGCC\3.3.1.27\AVRToolchain\bin\avr-gcc.exe” -o AVRGCC4.elf AVRGCC4.o lcd.o -Wl,-Map=”AVRGCC4.map” -Wl,-lm -Wl,-l libprintf_flt -Wl,-lm -Wl,-u,vfprintf -lprintf_flt -lm -mmcu=atmega32
    avr-gcc.exe: libprintf_flt: No such file or directory
    make: *** [AVRGCC4.elf] Error 1
    Done executing task “RunCompilerTask” — FAILED.
    Done building target “CoreBuild” in project “AVRGCC4.cproj” — FAILED.
    Done building project “AVRGCC4.cproj” — FAILED.

    Build FAILED.
    ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

Leave a Reply