如何在不为 arduino 使用 sstream 的情况下将浮点值转换为字符串?

How do I convert float value to string without using sstream for arduino?

我有一个连接到 Yún shield 的 DHT11 传感器,我正在使用 DHT 库从传感器读取数据:

indoorHumidity = dhtBedRom.readHumidity();
// Read temperature as Celsius
indorTempinC = dhtBedRom.readTemperature();
// Read temperature as Fahrenheit
indorTempinF = dhtBedRom.readTemperature(true);
// Compute heat index, Must send in temp in Fahrenheit!
hi = dhtBedRom.computeHeatIndex(indorTempinF, indoorHumidity);
hIinCel = (hi + 40) / 1.8 - 40;
dP = (dewPointFast(indorTempinC, indoorHumidity));
dPF = ((dP * 9) / 5) + 32;

然后我尝试将数据露点和温度、湿度和热量指数放入 BridgeClient 键,这样我就可以在呈现 HTML 的 python 程序中读取它并使用 Python 的 bottle wsgi 框架显示。

这些行产生错误:

Bridge.put(DEWPNTkey, dP);
Bridge.put(HEADINDXkey, hIinCel);

说:

no matching function for call to 'SerialBridgeClass::put(String&, float&)'

Bridge.put() method requires a char or a string as its second parameter. So we can use the String constructor 做到这一点。

void setup()
{
  Serial.begin(115200); // To test this make sure your serial monitor's baud matches this, or change this to match your serial monitor's baud rate.

  double floatVal = 1234.2; // The value we want to convert

  // Using String()
  String arduinoString =  String(floatVal, 4); // 4 is the decimal precision

  Serial.print("String(): ");
  Serial.println(arduinoString);

  // You would use arduinoString now in your Bridge.put() method.
  // E.g. Bridge.put("Some Key", arduinoString)
  // 
  // In your case arduinoString would have been dP or hIinCel.

  // In case you need it as a char* at some point
  char strVal[arduinoString.length() + 1]; // +1 for the null terminator.
  arduinoString.toCharArray(strVal, arduinoString.length() + 1);

  Serial.print("String() to char*: ");
  Serial.println(strVal);
}

void loop()
{

}

我们得到:

String(): 1234.2000
String() to char*: 1234.2000

前往 here 阅读有关空终止符的信息。