2

I need to convert a float value to a string in my avr project. Therefore I tried it with the following code:

char buf[10];
float emg1 = 33.42;
sprintf(buf, "%f", emg1);
uart_puts(buf);

But the output is only a "?". I tried to change the char format from %f to %g but I only got "?".

Is there another way to simply convert float to string, or can somebody tell me where the mistake is?

kaan5353
  • 67
  • 5
  • Maybe your printf implementation doesn't support %f. Did you double check with e.g. `sprintf(buf, "%d", 123)` just to be sure that the problem is not elsewhere? – Jabberwocky Apr 28 '22 at 12:33
  • I don't see the issue with string conversion. Sometimes due to sync error bits are wrongly interpreted. – TruthSeeker Apr 28 '22 at 12:34
  • with %d and a int it works – kaan5353 Apr 28 '22 at 12:34
  • @kaan5353 then clearly your printf implementation doesn't support %f. That should be somewhere in the documentation. – Jabberwocky Apr 28 '22 at 12:36
  • 2
    `-Wl,-u,vfprintf -lprintf_flt -lm` has to be enabled for `float`, as per `avr` [doc](https://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html#gaa3b98c0d17b35642c0f3e4649092b9f1). – TruthSeeker Apr 28 '22 at 12:43
  • 1
    Tip: `sprintf(buf, "%f", emg1);` is not certainly enough info to convert the string back to the same `float`. Better as `sprintf(buf, "%.8e", emg1);` or `sprintf(buf, "%.9g", emg1);` with a larger buffer (about 17+). – chux - Reinstate Monica Apr 28 '22 at 12:46

0 Answers0