Arduino sprintf float 未格式化

新手上路,请多包涵

我有这个 arduino 草图,

 char temperature[10];
float temp = 10.55;
sprintf(temperature,"%f F", temp);
Serial.println(temperature);

温度打印为

? F

关于如何格式化这个浮点数的任何想法?我需要它是一个字符字符串。

原文由 Mistergreen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

由于某些性能原因 %f 不包含在 Arduino 的 sprintf() 实现中。更好的选择是使用 dtostrf() - 您将浮点值转换为 C 风格的字符串,方法签名如下所示:

 char *dtostrf(double val, signed char width, unsigned char prec, char *s)

使用此方法将其转换为 C-Style 字符串,然后使用 sprintf,例如:

 char str_temp[6];

/* 4 is mininum width, 2 is precision; float value is copied onto str_temp*/
dtostrf(temp, 4, 2, str_temp);
sprintf(temperature,"%s F", str_temp);

您可以更改最小宽度和精度以匹配您正在转换的浮点数。

原文由 Dinal24 发布,翻译遵循 CC BY-SA 3.0 许可协议

我已经努力了几个小时才能做到这一点,但我终于做到了。这使用了 Platformio 提供的现代 Espressif C++,我的目标 MCU 是 ESP32。

我想显示一个前缀标签,float/int 值,然后是单位,都是内联的。

由于我使用的是 OLED 显示器,因此我无法使用单独的 Serial.print() 语句。

这是我的代码示例:

   int strLenLight = sizeof("Light ADC: 0000");
  int strLenTemp = sizeof("Temp: 000.0 °C");
  int strLenHumd = sizeof("Humd: 00.0 %");

  char displayLight[strLenLight] = "Light ADC: ";
  char displayTemp[strLenTemp] = "Temp: ";
  char displayHumd[strLenHumd] = "Humd: ";

  snprintf(strchr(displayLight, '\0'), sizeof(displayLight), "%d", light_value);
  snprintf(strchr(displayTemp, '\0'), sizeof(displayTemp), "%.1f °C", temperature);
  snprintf(strchr(displayHumd, '\0'), sizeof(displayHumd), "%.1f %%", humidity);

  Serial.println(displayLight);
  Serial.println(displayTemp);
  Serial.println(displayHumd);

其中显示:

 Light ADC: 1777
Temp: 25.4 °C
Humd: 55.0 %

原文由 Excalibur 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题