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