Can't connecting to MQTT broker

Hi guys. I want to sending data from MEGA2560 with ESP8266 to MQTT server but but did't succeed. Can anyone tell me the solution to this problem?

here the Serial output info:

12:48:42.274 -> [WiFiEInitializing ESP module
12:48:42.274 -> [WiFiEsp] Initializing ESP module
12:48:45.724 -> [WiFiEsp] Initilization successful - 2.0.0
12:48:45.724 -> Attempting to connect to WPA SSID: MikroTik Tesla
12:48:50.726 -> [WiFiEsp] Connected to MikroTik Tesla
12:48:50.726 -> You’re connected to the network
12:48:50.726 -> Attempting to connect to the MQTT broker: 10.5.51.9
12:48:50.760 -> [WiFiEsp] Connecting to 10.5.51.9
12:49:20.777 -> [WiFiEsp] Disconnecting  3
12:49:20.777 -> MQTT connection failed! Error code = -1

and the arduino sketch:

#include <ArduinoMqttClient.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>

char ssid[] = "MikroTik Tesla";
char pass[] = "12345678";
int status = WL_IDLE_STATUS;

WiFiEspClient espClient;
MqttClient mqttClient(espClient);

IPAddress server(10, 5, 51, 9);
const char topic[]  = "real_unique_topic";

const long interval = 20;
unsigned long previousMillis = 0;

int count = 0;

void setup() {
  Serial.begin(115200);
  Serial1.begin(115200);
  WiFi.init(&Serial1);
  mqttClient.setId("MEGAs");
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    while (true);
  }
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
  }
  Serial.println("You’re connected to the network");
  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(server);
  if (!mqttClient.connect(server, 1883)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());
  }
  while (1);
  Serial.println("You're connected to the MQTT broker!");
  Serial.println();

}

void loop() {
  mqttClient.poll();
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    int Rvalue = analogRead(A0);
    Serial.print("Sending message to topic: ");
    Serial.println(topic);
    Serial.println(Rvalue);
    mqttClient.beginMessage(topic);
    mqttClient.print(Rvalue);
    mqttClient.endMessage();
    Serial.println();
  }
}

thanks for any help.

That's apparently MQTT_CONNECTION_TIMEOUT.

Can anything else on your network connect?

yes there is no problem with my network

Sure, but can anything hit the MQTT server?

yes with pubsubclient library I tested my MQTT broker and it's worked.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.