C++/Arduino 集成开发环境。将 float 发布到 MQTT - 是否需要转换为字符串 -> 数组?

标签 c++ arduino

我正在尝试在 Arduino IDE 中使用 C++ 将 float 发布到 MQTT channel 。

下面的代码看起来确实有效,但似乎有点啰嗦。我从网上找到的东西拼凑而成。这一切是否真的有必要(通过字符串转换为数组),还是有更好的方法?

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <SparkFunBME280.h>

BME280 atmosSensor;

String tStr;
String pStr;
String hStr;
char tArr[4];
char pArr[4];
char hArr[4];

void setup() {
    Setup wifi, mqtt, etc.
}


void loop() {
  float tempReading = atmosSensor.readTempC();
  float pressureReading = atmosSensor.readFloatPressure();
  float humidityReading = atmosSensor.readFloatHumidity();
  tStr = String(tempReading);
  pStr = String(pressureReading);
  hStr = String(humidityReading);
  tStr.toCharArray(tArr, tStr.length()+1);
  pStr.toCharArray(pArr, pStr.length()+1); 
  hStr.toCharArray(hArr, hStr.length()+1); 
  client.publish("atmos1/temperature", tArr);
  client.publish("atmos1/pressure", pArr);
  client.publish("atmos1/humidity", hArr);
}

注意我已将这段代码大幅缩减,只保留相关部分。我真的只是想问是否有必要先转换为字符串,然后再转换为数组等。

最佳答案

您可以使用 dtostrf 以更少的步骤进行转换。

char* dtostrf(double __val, signed char __width, unsigned char __prec, char * __s )

它看起来像这样:

 void loop()    
 {
    float humidityReading = atmosSensor.readFloatHumidity();
    constexpr size_t BUFFER_SIZE = 7; //1 char for the sign, 1 char for the decimal dot, 4 chars for the value & 1 char for null termination
    char buffer[BUFFER_SIZE]; 
    dtostrf(humidityReading, BUFFER_SIZE - 1 /*width, including the decimal dot and minus sign*/, 2 /*precision*/, buffer);
    client.publish("atmos1/humidity", buffer, BUFFER_SIZE); //notice we're using the overload where you specify the length of the buffer, as we know it and it saves a call to strlen
 }

粗略浏览一下 MQTT 源代码可以看出,在调用 publish() 之后,数据存储在内部缓冲区中,因此您应该安全地为多次调用重用同一缓冲区发布()。但一定要比我检查得更彻底 ;)

关于C++/Arduino 集成开发环境。将 float 发布到 MQTT - 是否需要转换为字符串 -> 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57959969/

相关文章:

c++ - __attribute__((destructor)) 在 VC 中等效?

c++ - 错误 : 'track_t' was not declared in this scope

arduino - 除法 float 时丢失数字 C++ (Arduino)

c++ - 如何在 C++ (Arduino/C++) 中将字符串转换为 uint8_t?

c++ - 使用 I2C 发送 0x00

c++ - 采用一种显式类型的函数

c++ - CRTP相对于抽象类的好处?

c++ - 应用间接时,标准是否要求指针变量的左值到右值转换?

c++ - 从字符串中提取字母并转换为大写?

arduino - 为什么我的 ESP8266 的 EEPROM 不工作?