I am getting a bit confused and I need some help.The following code works fine:
const uint8_t MESSAGE_MAX_SIZE = 10;
char message[MESSAGE_MAX_SIZE];
uint8_t val ;
val = 99;
(void)snprintf(message, MESSAGE_MAX_SIZE,"%d", val);
Serial.println(message);whereas the following does not:
const uint8_t MESSAGE_MAX_SIZE = 10;
char message[MESSAGE_MAX_SIZE];
float val ;
val = 1.23;
(void)snprintf(message, MESSAGE_MAX_SIZE,"%f", val);
Serial.println(message);Firstly, I get the following warning:
(32 of 107): warning: format '%f' expects argument of type 'double', but argument 4 has type 'float' [-Wformat=]
and what I get from the serial is the character ?.
If I accommodate the warning with e.g.:
(void)snprintf(message, MESSAGE_MAX_SIZE,"%f", (double)val);
then I get the same result, i.e. ? from the serial.
Useless messages using < sprintf() and snprintf()>
arduino - Custom snprintf() function gives wrong output - Stack Overflow
c string - snprintf doesn't display float values - Arduino Stack Exchange
how to snprintf to serial with String object type ?
Arduino's implementation of snprintf has no floating-point support. Had to use dtostrf instead (http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga060c998e77fb5fc0d3168b3ce8771d42).
So instead of doing:
char temp[100];
float f;
f = 1.23;
snprintf(temp, 100, "%f", f);
Using the Arduino i had to do:
char temp[100];
float f;
f = 1.23;
dtostrf(f , 2, 2, temp); //first 2 is the width including the . (1.) and the 2nd 2 is the precision (.23)
These guys had figured that out on the avrfreaks forum: http://www.avrfreaks.net/index.php?name=PNphpBB2&file=printview&t=119915
Considering what you meant is
char temp[100];
float f;
f = 1.23;
snprintf(temp, 100, "%f", f);
it works as it's supposed to.