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 ?
I have some old code that might help if you want to avoid the printf entirely and simply need to print with a given number of digits before and after the decimal. This code compiles in C and works fine in the Arduino IDE as well. It could almost certainly be done in fewer lines of C++. The pow10 could be done programmatically, but powers weren't supported in the version of C I was working with:
You can play with it and see it run here: http://ideone.com/AtYxPQ
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.From
avr-libc
documentation:Note that if your MCU doesn't have any floating point support, you should try to avoid floating point operations completely. The floating point operations will be done in software which is very inefficient and needs a lot a flash memory.
I did this one:
and now i get an ascii char when i send a value from 0-255 through the usb. I should find a way to convert the ascii char to int.
e.g i type 65 and it prints A