You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP8266连接aREST.io MQTT broker失败(rc=-2)求助

问题:ESP8266无法连接aREST.io MQTT Broker

一个月前我编写代码上传至NodeMCU(ESP8266),实现其与aREST.io MQTT broker的连接,当时运行正常。现在设备无法连接该broker,连接WiFi后串口监视器打印:Attempting MQTT connection...failed, rc=-2 try again in 5 seconds。我已多次核对API key确认无误,用Wireshark分析网络发现ESP8266每5秒向broker发送CONNECT数据包,broker回复CONNACK数据包,但连接仍失败。

运行过的代码

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>

WiFiClient espClient;
PubSubClient client(espClient);

aREST rest = aREST(client);

char* key = "the api key in aREST account";
const char* ssid = "SSID";
const char* password = "Pass";

#define trigger 5
#define echo 4
float distance;

void callback(char* topic, byte* payload, unsigned int length);

void setup(void)
{

  Serial.begin(115200);
  pinMode(trigger, OUTPUT);
  pinMode(echo, INPUT);
  
  rest.setKey(key);
  client.setCallback(callback);
  rest.variable("distance",&distance);

  rest.set_name("esp8266");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

}

void loop() {
rest.handle(client);

digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);

int timin = pulseIn(echo,HIGH);
distance = (171.5*((timin)))*10E-5;
delay(60);
  
  
  rest.publish(client, "distance", distance, 60000);

}
void callback(char* topic, byte* payload, unsigned int length) {

  rest.handle_callback(client, topic, payload, length);

}

内容的提问来源于stack exchange,提问作者Kiroloes Amir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:25:27