[問題]esp8266連MQTT
是這樣的,目前利用nano+esp8266去連MQTT,但一直連
不上去,會出現
1547033662: New connection from 192.168.31.203 on port 1883.
1547033666: Socket error on client <unknown>, disconnecting.
想請教版上的各位有沒有解?以下是我的程式碼
#include <PubSubClient.h>
#include <WiFiEsp.h>
char LOG;
#define WIFI_SSID "!!!!!!" //填入WiFi帳號
#define WIFI_PASSWORD "!!!!!!!" //填入WiFi密碼
int WiFi_Status = WL_IDLE_STATUS; //WiFi狀態
const char* mqttServer = "192.168.31.72"; //填入MQTT Broker的IP或Domain
const int mqttPort = 1883; //MQTT Broker的Port
const char* clientID = "arduinoClient2"; //填入自訂ID
const char* topic = "QOO"; //填入自訂主題名稱(階層式命名)
#define N_SERVOS 6
WiFiEspClient espClient; //設定WiFiEspClient物件
PubSubClient client(espClient); //設定PubSubClient物件(帶入espClient)
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
//wifi設定
wifi_Setting();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
void reconnect() {
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
if (client.connect(clientID)) {
Serial.println("MQTT 已連接!");
} else {
Serial.print("失敗!, rc=");
Serial.print(client.state());
Serial.println("三秒之後重試...");
client.state();
delay(3000);
}
}
client.subscribe("QOO");
}
void callback(char*topic, byte* payload, unsigned int length) {
//Serial.print("Messagearrived in topic: ");
//Serial.println(topic);
//Serial.print("Message:");
LOG="";
for (int i = 0; i< length; i++) {
LOG=(char)payload[i];
Serial.print((char)payload[i]);
}
//Serial.print(LOG);
//
Serial.println();
Serial.println("-----------------------");
}
void wifi_Setting(){
//初始化ESP模組
WiFi.init(&Serial);
Serial.print("進行WiFi設定!\r\n");
do{
Serial.println("WiFi 連接中 ...");
WiFi_Status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
delay(1000);
} while (WiFi_Status != WL_CONNECTED);
Serial.print("WiFi 連接成功!\r\n");
reconnect();
Serial.println("WiFi 設定結束\r\n");
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.162.19.84
※ 文章網址: https://www.ptt.cc/bbs/ASM/M.1547033708.A.E2A.html
ASM 近期熱門文章
PTT數位生活區 即時熱門文章