Attempting MQTT connection...failed, rc=-2

Hi all. I was getting the error of "attempting MQTT connection...failed, rc=-2" when I was trying to connect to the MQTT broker by using the ESP-01 connected to the Arduino MEGA. I saw someone proposed adding the command WiFi.mode(WIFI_STA) before the wifi.begin. However, I did try and it was failed.

This is my code. Hope to get some review and thanks in advance.

#include "ESP8266WiFi.h"
#include "PubSubClient.h"

const char* ssid = "xxxxxx";
const char* password = "xxxxxxx";
const char* mqtt_server="xxxxxxx";

WiFiClient espclient;
PubSubClient client(espclient);

void setup()
{
pinMode(2,OUTPUT); //to blink LED
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("*");
}

Serial.println("");
reconnect();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void callback(char* topic,byte* payload,unsigned int length)
{
Serial.print("message arrived[");
Serial.print(topic);
Serial.println("]");

for(int i=0;i<length;i++){
Serial.print(payload*);*

}
if(payload[0]==49) digitalWrite(2,HIGH); //ASCII VALUE OF '1' IS 49
else if(payload[0]==50)digitalWrite(2,LOW);//ASCII VALUE OF '2' IS 50
Serial.println();
}
void reconnect(){

  • while(WiFi.status()!=WL_CONNECTED){*
  • delay(500);*
  • Serial.print(".");*
  • }*

while(!client.connected()){

  • Serial.print("Attempting MQTT connection...");*

  • // Create a random client ID*

  • String clientId = "ESP8266Client-";*

  • clientId += String(random(0xffff), HEX);*

  • if(client.connect("ESP8266Client")){*

  • Serial.println("connected");*

  • client.subscribe("LEDcontrol");*

  • }*

  • else{*

  • Serial.print("failed,rc=");*

  • Serial.println(client.state());*

  • delay(500);*

  • }*

  • }*
    }
    void loop() {

  • if(!client.connected()){*

  • reconnect();*

  • }*

  • client.loop();*
    }

if(payload[0]==49) digitalWrite(2,HIGH);    //ASCII VALUE OF '1' IS 49
else if(payload[0]==50)digitalWrite(2,LOW);//ASCII VALUE OF '2' IS 50

or

if(payload[0] == '1') digitalWrite(2,HIGH);    // No useless comment necessary
else if(payload[0] == '2')digitalWrite(2,LOW);// No useless comment necessary

You get SOME serial output that you failed to show. You failed to show any proof that you have an MQTT server running anywhere. You failed to show any proof that you even connect to the WiFi network. We can't guess at what the problem is with NO facts and data.

the picture show the serial monitor output and the mqtt connection in node-red.