Notes About Working with Various Arduino & Netduino Microcontroller Boards

Thursday, May 30, 2013

Arduino C Code to Convert a Float to a String

Here is a snippet of code that demonstrates using the dtostrf()function of the avr-gcc stdlib to convert a float value to a string (array of chars).

A call to dtostrf takes four arguments:

  1. A floating point value to be converted
  2. An integer indicating the minimum width (number of characters) for the output - including the decimal point and any leading minus sign.  The output will be padded on the left side with spaces if the overall output is shorter than this value.
  3. An integer to specify the number of digits to the right of the decimal place. The output will be padded with zeros on the right, if necessary. 
  4. An array of chars to hold the converted value.  Be sure the array has enough room for all characters in  output.

Be sure to include stdlib.h.

Here is the portion of Arduino C:

#include <stdlib.h>
.
.
.

float h = dht.readHumidity();
float t = dht.readTemperature() * 9/5 + 32;
char tempF[6]; // buffer for temp incl. decimal point & possible minus sign
char rhPct[6]; // buffer for humidity incl. decimal point
dtostrf(t, 6, 2, tempF); // Min. 6 chars wide incl. decimal point, 2 digits right of decimal
mySerial.write(tempF);
mySerial.write("F ");
dtostrf(h, 6, 2, rhPct);
mySerial.write(rhPct);
mySerial.write("%");
mySerial.write("\r\n");
.
.
.


Note (June 13, 2013):

/* As of early June 2013, dtostrf is not implemented in the Arduino IDE 1.5 libraries -
   but it will be implemented in the future. Use this function in the meantime
   See http://forum.arduino.cc/index.php?topic=170564.0. */
char *dtostrf (double val, signed char width, unsigned char prec, char *sout) {
  char fmt[20];
  sprintf(fmt, "%%%d.%df", width, prec);
  sprintf(sout, fmt, val);
  return sout;

}

No comments:

Post a Comment