Electronic – Arduino Sketch Compile Error: Trying to Concatenate Float with String

arduinocsoftware

I am not sure if I should be posting this here or on Stackoverflow, but since this audience likely has the most experience with Arduino, I figured this would be the best place.

I just bought an Ethernet shield, and as a first project with it, I'm trying to publish a TMP36 temperature reading to Pachube. While Pachube accepts multiple formats for your data, I'm trying to post this stuff in JSON, because I like JSON. However, I'm running into trouble getting my temperature value, which is a float, into the JSON string. I'm a Python/PHP developer, and relatively new to C, so I've googled a lot but haven't discovered the right way to do this yet. Here is my code:

float temperature = 85.4; // Or whatever
String jsonData = sprintf("{'version':'1.0.0', 'datastreams':[{'id':'%s', 'current_value':'%f'}]}\n", datastream1, temperature);

I keep getting the following error from the Arduino IDE (version 1.0): "Cannot convert 'String' to 'const char' for argument '2' to 'int sprintf(char, const char*, …)'"

I found out I am calling sprintf() with the wrong number of arguments/arguments in the wrong order, since it does not return the formatted string. However, I'm not even sure sprintf() is the best function to use to accomplish the goal of getting the sensor's floating point value into a string. Is there a better way to do this

Best Answer

You cannot use sprintf() to format a float into a string on the Arduino.

Not only is the format of the command wrong, but sprintf on the Arduino does not support floats.

There is a function dtostrf() which converts a float into a character array. You can use it like:

float temperature = 85.4;
char temp[10];
String tempAsString;
String jsonData;

dtostrf(temperature,1,2,temp);
tempAsString = String(temp);

jsonData = "{'version':'1.0.0', 'datastreams':[{'id':'" +
    datastream1 + "', 'current_value':'" + tempAsString + "'}]}\n";

The format of the dtostrf function is:

dtostrf(value, width, precision, output);

where value is the float value you wish to convert, width is the minimum number of characters to display before the decimal point (padding with spaces as needed), precision is the number of decimal places, and output is the character array to put the results in.