Esp-32 从 'const char*' 到 'int' 的无效转换 [-fpermissive]

Esp-32 invalid conversion from 'const char*' to 'int' [-fpermissive]

你好我有一些变量转换的问题,一个问题是当尝试编译代码时得到这个错误消息。为什么不能转换?

我把 wtrtemp 作为字符串尝试将其更改为 int 和 float 以及 const char 同样的问题。 Mqtt 只是从滑块打印出一个数字。从节点 red

发送

从 'const char*' 到 'int' 的无效转换 [-fpermissive]

//MQTT incoming
#define mqttFloodInterval "greenHouse/floodInt"
#define mqttFloodDuration "greenHouse/floodDur"
#define mqttLightsOnDuration "greenHouse/lightsOnDur"
#define mqttLightsOffDuration "greenHouse/lightsOffDur"
//MQTT Setup End
int wtrtemp;
void topicsSubscribe(){
   client.subscribe(mqttFloodInterval);
   client.subscribe(mqttFloodDuration);
   client.subscribe(mqttLightsOnDuration);
   client.subscribe(mqttLightsOffDuration);
}
  Serial.print("MQTT message received on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  messageTemp.remove(0);
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();
  Serial.println(messageTemp);
  if (String(topic) == mqttFloodDuration) {
    wtrtemp = mqttFloodDuration; // The problem is here 
    Serial.print("*** (Flood Interval Received)");
  }
  if(wtrtemp == 23){
 digitalWrite(15, HIGH); // turn on pump 5 seconds
     delay(5000);
  } 
     else {
     
       digitalWrite(15, LOW);  // turn off pump 5 seconds
      delay(5000);
  }
}

我没有测试你的案例的环境,但我强烈建议你是否尝试将字符串转换为你使用 atol() 的 int,因为 esp32 框架支持它。

int x = (int)atol("550");

所以在你的情况下:wtrtemp = (int)atol(mqttFloodDuration); // The problem is here

如果这不能解决您的问题(不能 100% 记住 atol 使用的参数是否采用 const char* 或 char*),所以如果它坚持使用 char*,请尝试改用它: wtrtemp = (int)atol((char*)mqttFloodDuration); // The problem is here

如果你想继续使用 String class 的危险但容易的道路,那么你可以很容易地设置一个 String

String xx = "hello world";
int xx_int = xx.toInt();

但在底层,该函数也执行上面提到的 atol() 函数,因此如果您想要提高内存分配和 esp32 板载 ram 的使用效率,请记住这一点。

您的 mqttFloodDuration 是一个扩展为字符串文字 "greenHouse/floodDur" 的宏。错误消息正确地告诉您,这与 int 类型的变量类型不匹配,例如您的 wtrtemp.

此外,您似乎确实期望 wrtemp 取一个真正的整数值,因为稍后您将它与整数常量 23 进行比较,但从代码中不清楚字符串 23 是如何呈现的=11=]对应一个整数。可能有某种查找函数可用于获取相应的值,但据我所知,这将特定于您的项目。