你好,我有一些变量转换的问题,一个问题是,当尝试编译代码时,会得到这个错误消息。为什么它不能转换?
我将wtrtemp
作为字符串,尝试将其更改为整型、浮点型和常量字符,同样存在问题。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);
}
}
发布于 2020-12-17 20:53:09
我没有测试你的用例的环境,但是我强烈建议你在尝试将一个字符串转换成int时使用atol(),因为esp32框架支持它。
int x = (int)atol("550");
因此,在您的示例中:wtrtemp = (int)atol(mqttFloodDuration); // The problem is here
如果这不能解决您的问题(不能100%记住atol use参数是否接受了常量char*或char*),那么如果它坚持使用char*,请尝试使用以下内容:wtrtemp = (int)atol((char*)mqttFloodDuration); // The problem is here
如果您希望走上使用String类的危险但简单的道路,那么您可以很容易地通过以下方式设置字符串
String xx = "hello world";
int xx_int = xx.toInt();
但是在底层,这个函数也做上面提到的atol()函数,所以如果你想高效地分配内存和使用esp32板载ram,请记住这一点。
发布于 2020-12-17 20:58:26
您的mqttFloodDuration
是一个展开为字符串文字"greenHouse/floodDur"
的宏。错误消息正确地告诉您,这与类型为int
的变量(如您的wtrtemp
)的类型不匹配。
此外,您似乎确实希望wrtemp
接受一个真正的整数值,因为您稍后会将它与整数常量23
进行比较,但是从所给出的代码中不清楚字符串"greenHouse/floodDur"
如何对应于整数。可能有某种查找函数可以用来获得相应的值,但据我所知,这将特定于您的项目。
https://stackoverflow.com/questions/65340999
复制相似问题