Arduino: printf/fprintf prints question mark instead of float

Nicu Surdu picture Nicu Surdu · Jan 3, 2013 · Viewed 15.2k times · Source

I have the following code for an Arduino sketch:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
static FILE lcdout = {0} ;

static int lcd_putchar(char ch, FILE* stream)
{
    lcd.write(ch) ;
    return (0) ;
}

void setup() {
  lcd.begin(16, 2);
  fdev_setup_stream (&lcdout, lcd_putchar, NULL, _FDEV_SETUP_WRITE);
}

void loop() 
{
  stdout = &lcdout;
  printf("%.2f Volts", 2.0);
}

The problem comes at the last line of the code. This should print out "2.00 Volts" but instead, it prints "? Volts" (a question mark instead of the actual float value). If I try to format an integer, this works great.

So basically, if I replace the printf line with the following, it will work properly:

printf("%d Volts", 2); //prints correctly "2 Volts"

Any idea what's the problem ?

Answer

user529758 picture user529758 · Jan 3, 2013

The GNU toolchain for AVRs (which is included with the Arduino IDE) uses a "minified" version of the C standard library by default, in which, for example, the floating-point support is reduced/taken away from formatted I/O functions (just in order printf() to fit in the few kBytes long storage of the chip.)

If you want this to work, you have to link agains another library containing the normal version of printf(), by using the -Wl,-u,vfprintf -lprintf_flt linker flags.