I just changed to an MI 3C router from a Dlink.
I had to do a router reboot a couple of times and all my ESPs all over the place lost connection. I had to do a physical power on/off to get them all back on line. I believe ESP has a inbuilt auto connect feature ?
Sorry I have a very poor knowledge of coding and bad with English, I am a biotechnologist professional.
I have similar code running on another 12 ESPs doing various things like running Drip Irrigation systems, checking moisture levels etc. This particular one is used to notify me when a bell push button is pressed and toggle a light.
Also if possible please suggest any improvements to the code.
Thanks
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
const char* ssid = "Ven Res";
const char* password = "venhazari";
const char* mqtt_server = "192.168.0.103";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
char msg2[50];
int value = 0;
const int Bell = D2;
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.persistent(false);
WiFi.mode(WIFI_OFF); // this is a temporary line, to be removed after SDK update to 1.5.4
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if ((char)payload[0] == '0') {
digitalWrite(D1, HIGH);
} else {
digitalWrite(D1, LOW);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
Serial.println (clientId.c_str());
client.subscribe("WashLight");
} else {
delay(5000);
}
}
}
void setup() {
ArduinoOTA.begin();
pinMode(Bell, INPUT_PULLUP);
pinMode(D1, OUTPUT);
//digitalWrite(D1,HIGH);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
ipaddress();
if (!client.connected()) {
reconnect();
}
if (digitalRead(Bell) == LOW) {
client.publish("BellOut", "Bell Pressed");
delay (500);
} else {
client.publish("BellOut", "Bell Open");
}
client.loop();
long now = millis();
if (now - lastMsg > 18000) {
lastMsg = now;
++value;
snprintf (msg, 75, "Bell #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("Bell_Status", msg);
sprintf(msg2, "%ld", (2*(WiFi.RSSI()+100)));
client.publish("Bell", msg2);
}
ArduinoOTA.handle();
}