Help me convert float to string before posting to pachube

27 Jul 2011

I have a float, power, and want to post it to Pachube as a string. The Pachube example post data in the form of a string for example: string data = "123"; But I want it to be something like this: string data = floattostring(power); How do I do that? See below for snippets of my code

float power,time_s;

void flip() {// this interupt measures time between two flashes of the powermeter LED
    time_s = t.read(); // read timer
    power=3600/time_s; //calculate power
}

int main() {
    while (true) {        
                if (t_pachube.read()>120) {
                    t_pachube.reset();
                    string apiKey = "mykey"; // copy API key from settings
                    string environmentID = "myID";// use feed ID
                    string datastreamID = "0"; // use datastream ID
//LOOK HERE         string data = "123"; <-- this data is used in the example
                    // what need to be put here??
                    // I want to convert the float to string
//UNTIL HERE
                    HTTPClient client;// for authentication, API key is set in client header
                    client.setRequestHeader("X-PachubeApiKey", apiKey);
                    HTTPText csvContent("text/csv"); // text object holds data to be posted
                    csvContent.set(data);
                    string uri = "http://api.pachube.com/v1/feeds/" + environmentID + "/datastreams/" + datastreamID + ".csv?_method=put"; // uri for post includes feed ID and datastream ID
                    HTTPResult result = client.post(uri.c_str(), csvContent, NULL);// result should be 0 and response should be 200 for successful post
                    int response = client.getHTTPResponseCode();
                    printf("Pachube put response: %i\r\n",response);
                    led3=!led3; //toggle led
                }
    }//end of while(true) loop
}//end of main
27 Jul 2011

Try sprintf - see here for reference: http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

Mike

27 Jul 2011

Thanks for your reference Mike, this is the solution

char buffer [10];
//string data = "250"
sprintf (buffer, "%4.0f",power);// datastream value
string data = buffer;

Can be valuable to put in the cookbook