Logging and converting float values to Strings on Arduino

In Arduino You can use String class, which can be used to create log messages. Often You need to add some numeric values in this messages.

It can be simple as that code:

  String cmd = "curl --data \"key="+key;
  for (int i=0;i<ARRAY_SIZE;i++) {
    cmd = cmd + "&field"+ (i+1) + "=" + value[i];
  }
  cmd = cmd + "\" http://api.thingspeak.com/update";

You may recognize that code from our previous work with Arduino YUN. After few days I have noticed one thing. All float values are converted to string with only two decimal places. For small values it can have an impact. We measure voltage on MQ5 and MQ9 sensor, and it is quite low (0.1V). Using internal 2.56 V reference will yield with ADC resolution 2.56/1023 = 0.00250. If float values are rounded to 2 decimal places You will lose some information – value will be rounded (or truncated I’m not sure if it will be floored or rounded) to two decimal points and ThingSpeak will not log accurate result.

There are two solutions – first is to log analogRead result directly (without converting it to voltage). That way You will log integers (results of analogRead calls). But this method will produce data which are hard to compare. If You change ADC reference voltage You can not compare (at least directly) new results with some older data.

Arduino: convert float to strings done better way

Second solution is to make floats convert to strings with more decimal places. You can do this directly with String(NUMBER, SCALE);, so String(3.141592,5) will create string with 3 decimal places: "3.14159". How code sending data to ThingSpeak will look after changes?

  String cmd;
  String tmp;
  cmd = "curl --data \"key=" + key;
  for (int i=0;i<ARRAY_SIZE;i++) {
    tmp = String(value[i],5);
    cmd = cmd + "&field"+(i+1) + "=" + tmp;
  }
  cmd = cmd + "\" http://api.thingspeak.com/update";