我对 Arduino、编码和 MQTT 等都是菜鸟。
尝试发送“Hello World”到 MQTTX 以验证其连接
“尝试 MQTT 连接...失败,状态 = -2”
当我通过Wowki模拟时,它能够连接到MQTTX
代码有什么问题,如何解决?
任何帮助表示赞赏!
#include <WiFi.h>
#include <Wire.h>
#include <WiFiClient.h>
#include <WiFiAP.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
const char* ssid = "YourWiFi";
const char* password = "YourPassword";
//MQTT Broker Config
const char* mqtt_broker = "broker.emqx.io";
const char* topic = "customtopicname";
const char* mqtt_username = "customusername";
const char* mqtt_password = "custompassword";
const int mqtt_port = 1883;
String stMac;
char mac[50];
String ip;
WiFiServer server(80);
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
// searches and connects to WiFi access point specified in variable declaration
void initWiFi()
{
delay(10);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
ip = WiFi.localIP().toString();
Serial.println(ip);
Serial.println(WiFi.macAddress());
stMac = WiFi.macAddress();
stMac.replace(":", "_");
Serial.println(stMac);
server.begin();
}
// connection to MQTT server
void mqttConnect()
{
mqttClient.setServer(mqtt_broker, mqtt_port);
while (!mqttClient.connected())
{
Serial.printf("The client %s connects to the public MQTT broker\n", "mqttx_cbb540d9");
if (mqttClient.connect("custom_client_id_name", mqtt_username, mqtt_password))
{
Serial.println("Public EMQX MQTT broker connected");
}
else
{
Serial.print("failed with state ");
Serial.println(mqttClient.state());
delay(5000);
}
}
}
// the setup function runs once when you press reset or power the board
void setup()
{
Serial.begin(115200);
initWiFi();
}
// the loop function runs over and over again until power down or reset
void loop()
{
if (!mqttClient.connected())
{
mqttConnect();
}
mqttClient.loop();
//MQTT Server
mqttClient.publish(topic, "Hello world", true);
}
尝试将 ESP32 板连接到 MQTTX 服务器。能够通过 Wokwi 连接,但无法通过 Arduino 连接。
可能发生的情况是您没有设置正确的板。您能否提供有关您正在使用的主板以及正在配置的内容的更多信息?您使用的是 ArduinoIDE 还是 PlatformIO?
我建议使用 PlatformIO,如果您在 C/C++ 方面更有经验,我建议您直接使用 ESP-IDF 及其 MQTT 实现。