In any other C/C++ platform, you can use "%f" as a format specifier when you want to print (or convert to string) a float using printf
or its siblings. Any, except in Arduino.
To convert a float you need use dtostrf()
,
char * dtostrf(
double __val,
signed char __width,
unsigned char __prec,
char * __s)
The dtostrf() function converts the double value passed in val into an
ASCII representationthat will be stored under s. The caller is
responsible for providing sufficient storage in s.
Conversion is done in the format "[-]d.ddd". The minimum field width
of the output string (including the possible '.' and the possible sign
for negative values) is given in width, and prec determines the number
of digits after the decimal sign. width is signed value, negative for
left adjustment.
The dtostrf() function returns the pointer to the converted string s.
To convert a byte (or anything not float) to ascii, use snprintf()
int snprintf ( char * s,
size_t n,
const char * format,
... );
Write formatted output to sized buffer.
Composes a string with the same
text that would be printed if format was used on printf, but instead
of being printed, the content is stored as a C string in the buffer
pointed by s (taking n as the maximum buffer capacity to fill).
You can read the details by yourself, but here is a demo.
The idea is to produce in buffer
a traditional C-style string (null terminated). That string you can print or transmit.
The float value is printed in two step. First, we use dtostrf
to convert the float value to his ascii representation. Then we use snprintf
to include that value (as a string) inside a whole line, latter to be printed.
void setup() {
Serial.begin(9600);
while(!Serial);
Serial.println("Start");
float value = 123.45;
byte balue = 128;
char buffer[80];
char fValue[16];
dtostrf(value, 3, 2, fValue);
snprintf(buffer, sizeof(buffer), "float %s", fValue);
Serial.println(buffer);
snprintf(buffer, sizeof(buffer), "byte value is %d", (int) balue);
Serial.println(buffer);
}
void loop() {
}
dtostrf()
...