如何修复我使用过的 arduino 库之一的构造函数中的转换错误

How to fix conversion error in a constructor in one of my used arduino libraries

我正在尝试让两个 LoRa-esp32 相互通信,但是我的 "MASTER" 需要将从 "SLAVE" 接收到的传感器读数发送到我的 MQTT 服务器(使用 io.adafruit).由于某种原因,我无法将数据发送到 MQTT 服务器。我什么都试过了,但我不明白为什么会这样。

我阅读了该函数的 .h 构造函数,但我似乎不明白它有什么问题。

这是我的发布功能代码:

if (! Text1.publish(msg)) {
  Serial.println(F("Failed"));
} else {
  Serial.println(F("OK!"));
}

这是对应的Adafruit_MQTT.h库代码:

class Adafruit_MQTT_Publish {
 public:
  Adafruit_MQTT_Publish(Adafruit_MQTT *mqttserver, const char *feed, uint8_t qos = 0);

  bool publish(const char *s);
  bool publish(double f, uint8_t precision=2);  // Precision controls the minimum number of digits after decimal.
                                                // This might be ignored and a higher precision value sent.
  bool publish(int32_t i);
  bool publish(uint32_t i);
  bool publish(uint8_t *b, uint16_t bLen);


private:
  Adafruit_MQTT *mqtt;
  const char *topic;
  uint8_t qos;
};

This is the error I get:

Master:189:42: error: cannot convert 'String' to 'const char*' in initialization

const char *msg = createJsonString();

exit status 1 cannot convert 'String' to 'const char*' in initialization

编辑

按照评论中的要求将 Master:168 中的代码添加到 Master:202

void receive(){
  //Tentamos ler o pacote
  int packetSize = LoRa.parsePacket();

  //Verificamos se o pacote tem o tamanho mínimo de caracteres que esperamos
  if (packetSize > SETDATA.length()){
    String received = "";
    //Armazena os dados do pacote em uma string
    for(int i=0; i<SETDATA.length(); i++){
      received += (char) LoRa.read();
    }

    //Se o cabeçalho é o que esperamos
    if(received.equals(SETDATA)){
      //Fazemos a leitura dos dados
      LoRa.readBytes((uint8_t*)&data, sizeof(data));
      //Mostramos os dados no display
      showData();

      Serial.print("Publish message: ");
      //Criamos o json que enviaremos para o server mqtt
      const char *msg = createJsonString();
      Serial.println(msg);
      //Publicamos no tópico onde o servidor espera para receber 
      //e gerar o gráfico
      //client.publish(TOPIC_NAME, msg.c_str());
      //#define TOPIC_NAME "iot-2/evt/status/fmt/json"
         if (! Text1.publish(msg)) {
          Serial.println(F("Failed"));
        } else {
          Serial.println(F("OK!"));
        }
    }
  }
}

看起来确实是类型不匹配。根据编译器错误,createJsonString() returns 一个字符串对象。在 C++ 中,这与字符数组 不同 。我建议您花点时间熟悉 std::string,建议将 msg 转换为字符串对象(如 jxh)并使用 c_str() 函数来访问字符数组。

good description of string object