基本上我的代码看起来像这样:
void SimpleMQTT :: begin(){ Serial.println( “setserver”); WiFiClient espClient; PubSubClient客户端(espClient); client.setServer(这 - > …
你好像有一个悬垂的指针问题。 您在堆栈上创建客户端对象:
PubSubClient client(espClient);
然后参考它:
this->client = & client;
但是,一旦功能 SimpleMQTT::begin() 退出, client 被删除以及函数堆栈的其余部分。
SimpleMQTT::begin()
client
您应该在堆上创建客户端对象。 将代码更改为:
void SimpleMQTT::begin() { Serial.println("setserver"); WiFiClient* espClient = new WiFiClient(); PubSubClient* client = new PubSubClient(espClient); // Allocate an object on the heap client.setServer(this->serverAddress, this->port); while(!client->connected()) { if (client->connect(this->deviceName)) { Serial.println("connected to mqtt"); client->publish("connecting", "connected"); } else { Serial.println("failed to connect"); } } this->client = client; this->client->publish("connecting","conn2"); }
espClient 也应该是你班上的一员。
espClient
这是一个更精细的解释 丹琳指针 。