I have searched a lot regarding this problem but unable to find a solution. I have connected my esp8266 with mqtt broker successfully and is working perfectly. Now I want to make IP static so I've used wifi.config(ip, gateway, subnet) to do the same but now the connection with my mqtt broker fails with state -2. Both the codes i.e. wifi.config() and mqtt connection code works perfect independently but not together. I am using node mcu esp8266 board. Code is given below:-
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "ai***l";
const char* password = "j***se";
const char* mqttServer = "i***l.c****tt.com";
const int mqttPort = 1**8;
const char* mqttUser = "w*****e";
const char* mqttPassword = "H*******7";
IPAddress staticIP(192, 168, 1, 200);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
int led = D1;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
WiFi.config(staticIP, subnet, gateway); //problem with this line
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
delay(500);
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.println(client.state());
delay(2000);
}
}
client.subscribe("esp/node");
delay(500);
pinMode(led, OUTPUT);
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println((char) payload[0]);
}
void loop() {
client.loop();
}
Please help me to find a solution to this problem.