If I understand correctly, default Arduino versions of printf() and related functions do not support conversion of float type variables, as noted in this thread and many other places. A common suggestion is to use dtostrf() to convert the float variable to a char array variable then use that in printf().
I tried to be clever and make my code more compact by defining a similar function which, rather than modifying a passed-by-reference buffer, generates and returns a pointer to a char array so that I could use the returned char array directly inline inside my printf's. Based on this thread, I prototypes the following (demo):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
const char* floatToStr(float val, int decimalPlaces);
int main()
{
float speed[] = {234.5634, 43.234};
printf("speed0: %s, speed1: %s\n", floatToStr(speed[0],2), floatToStr(speed[1],2));
return 0;
}
const char* floatToStr(float val, int decimalPlaces){
char formatStr[12];
char *outstr = malloc(17);
if(decimalPlaces==0){
snprintf(outstr,16,"%i", (int)val );
} else {
snprintf(formatStr,10,"%%i.%%0%ii",decimalPlaces);
snprintf(outstr,16,formatStr, (int)val, ((int)((val>0?1:-1)*val*pow(10,decimalPlaces))%(int)pow(10,decimalPlaces)) );
}
return outstr;
}
It works! Or so it seemed. I had overlooked a comment in the second thread noted above regarding needing to free the buffer that was malloc'ed in the floatToStr function. Failing to free the buffer constitutes a memory leak.
I believe the best solution may be to follow the model provided in that thread about making a dedicated char buffer in the calling function and using dtostrf() to write to that buffer before calling printf, and forget about generating the full string purely inline. But before I give up hope on this method...
Question 1: can someone confirm (or guide me on how to confirm this myself) that the buffer that gets generated by floatToStr does not automatically get cleaned up (freed) after the printf is done?
Question 2: Is there some other way to keep the syntax at the caller level short and sweet, i.e. without needing to define the char array buffers outside of the printf call?