1

I'm using snprintf in arduino to print a float to a character *. I'm currently having issues reading the actual value because of some bugs, but thats not the actual question here. The string i am getting is simply containing "?". I was wondering if this is NaN or INF?

example:

char temp[100];
float f; //This float is initialised on some value, but i'm currently not really sure what this value is, but for example 1.23
f = 1.23
snprintf(temp, 100, "%f", f);

temp now simply contains "?".

Daniel
  • 8,655
  • 5
  • 60
  • 87
Mahogany
  • 73
  • 1
  • 8
  • You haven't initialized f to any value. – Alan Jun 03 '14 at 14:15
  • I purposely left that out because im not really sure what value is in the float – Mahogany Jun 03 '14 at 14:18
  • Quick search on `arduino printf float` seems to indicate the printf functions' family may not support floats by default... [possible answer](http://stackoverflow.com/questions/14146850/arduino-printf-fprintf-prints-question-mark-instead-of-float) – François Moisan Jun 03 '14 at 14:45
  • I'm not convinced. I'd be more interested in how you are using `temp` as a C string. – Brett Hale Jun 03 '14 at 15:57

2 Answers2

6

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

Mahogany
  • 73
  • 1
  • 8
  • 1
    Just in case you missed my comment, you can also enable support for it if you look at [this answer](http://stackoverflow.com/questions/14146850/arduino-printf-fprintf-prints-question-mark-instead-of-float). – François Moisan Jun 04 '14 at 15:16
-3

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.

ColonelMo
  • 134
  • 1
  • 9
  • It doesnt, the string contains "?" on arduino. – Mahogany Jun 03 '14 at 14:56
  • Um ... I tested it on both Windows and Ubuntu using g++ it works fine . – ColonelMo Jun 03 '14 at 15:05
  • Arduino doesn't use g++ and it does not use the standard gcc libraries either. – Mahogany Jun 04 '14 at 09:54
  • Rated down because it ignores the poster's context. The above code works on any complete implementation - but the arduino being a small platform is incomplete, and doesn't implement %f - which surprises most people when they first come to this. (Surprised me) – Michael Sparks Aug 06 '14 at 13:57