ESP8266和Arduino之间的MQTT通信使用PubSubclient

3

我正在使用WiFiEsp库将ESP8266与Arduino配合使用。我想使用PubSubclient库建立Arduino和MQTT服务器之间的连接,但是出现了错误:

尝试建立MQTT连接...失败,rc=-2,5秒后重试

这是我的代码:

#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>
#include "SoftwareSerial.h"
#include <PubSubClient.h>

IPAddress server(212, 72, 74, 21);
char ssid[] = "atmel";           // your network SSID (name)
char pass[] = "bets56789";           // your network password
int status = WL_IDLE_STATUS;   // the Wifi radio's status

// Initialize the Ethernet client object
WiFiEspClient espClient;

PubSubClient client(espClient);

SoftwareSerial soft(2,3); // RX, TX
void setup() {
// initialize serial for debugging
Serial.begin(9600);
// initialize serial for ESP module
soft.begin(115200);
// initialize ESP module
 WiFi.init(&soft);

// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (true);
}

// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}

// you're connected now, so print out the data
Serial.println("You're connected to the network");
//delay(2000);
//connect to MQTT server
client.setServer(server, 1883);
client.setCallback(callback);
}

//print any message received for subscribed topic
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}

void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
client.loop();
}

 void reconnect() {
 // Loop until we're reconnected
 while (!client.connected()) {
 Serial.print("Attempting MQTT connection...");
 // Attempt to connect, just a name to identify the client
 if (client.connect("arduinoClient")) {
  Serial.println("connected");
  // Once connected, publish an announcement...
  client.publish("outSHADAB","hello world");
  // ... and resubscribe
  client.subscribe("inShadab");
  } else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  // Wait 5 seconds before retrying
  delay(5000);
  }
  }
  }

我正在使用WiFiEsp库将ESP8266与Arduino配合使用。我想通过Arduino建立MQTT连接,因此我使用了PubSubclient库。


我遇到了一个错误:rc=-2。 - shadab
我想使用Arduino UNO作为控制器,使用esp8266作为WiFi模块来进行MQTT协议的工作,所以我使用pubsubclient库来支持MQTT。我使用软件串口库连接esp8266。但问题是pubsub库客户端在软件串口上无法工作。所以我使用了WiFiEsp库,代码如描述所示。请帮助我。 - shadab
我有同样的问题。你现在有解决方案吗? - Pranav Goswami
还没有找到解决办法。 - shadab
1个回答

1
我认为PubSubClient不支持将WiFiEsp作为Arduino的网络层。
虽然文档中列出了ESP8266,但我认为这是直接在ESP8266硬件上运行PubSubClient。

我正在使用博客中展示的这个例子:链接 - shadab
这似乎是事实,一个问题已经在WiFiEsp存储库中提出:https://github.com/bportaluri/WiFiEsp/issues/40 - Brett Y

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接