I created an Arduino code that use the shiled ,and connect to Ethernet. it´s work good, but when the power of my house is off and then is back. Arduino can't connect to Ethernet again. i add functions to reconnect to Ethernet ,and reset the Arduino (in the code), but it doesn't work. it only when i desconnect manually the Arduino.
Why this happen ,and how i can resolve it?
#include <Ethernet.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <SPI.h>
IPAddress ip(192, 168, 140, 96);
IPAddress myDns(192, 168, 140, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress server(192, 168, 143, 4);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
const char* mqttServer = "192.168.143.4";
const int mqttPort = 1883;
const char* mqttUser = "------"; //I deleted the user and the password for the post
const char* mqttPassword = "-------";
const char* mqttTopic = "Textiles";
String clientAddress = "";
String mensajePub = "";
int32_t contMqtt = 0;
int32_t contconexion = 0;
String content = "";
String msjmqtt = "";
EthernetClient client;
PubSubClient clientPub (client);
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
Serial.print("Connection to Ethernet....");
if (Ethernet.begin(mac) == 0) {
Serial.println("[Error al configurar Ethernet usando DHCP]");
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("[Ethernet no está conectado o el módulo no funciona]");
} else if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("[El cable Ethernet no está conectado]");
}
Serial.println("Connecting with mac,ip,myDns, subnet...");
Ethernet.begin(mac, ip, myDns, subnet);
while (true) {
delay(1);
}
} else {
Serial.println("[Connected]");
}
FuncionClientPub();
}
void loop() {
Ethernet.maintain();
clientPub.loop();
verification();
}
void MqttRecived(char* topic, byte* payload, unsigned int length) {
Serial.print("MQTT Recived>>"); Serial.print("["); Serial.print(topic); Serial.println("]");
for (size_t i = 0; i < length; i++) {
content.concat((char)payload[i]);
}
Serial.print("Message>["); Serial.print(content); Serial.println("]<"); //String content = "";
int posSeparador = 0;
}
void FuncionClientPub() {
clientPub.setServer(mqttServer, mqttPort);
clientPub.setCallback(MqttRecived);
Serial.print("Connecting to Broquer Mqtt....");
while (!clientPub.connected() && contMqtt < 100) {
Serial.print(".");
contMqtt++;
if (clientPub.connect("Arduinoclient", mqttUser, mqttPassword)) {
clientPub.subscribe(mqttTopic);
Serial.println("[Connected]");
}
}
Serial.print("Mqtt....");
if (contMqtt < 100) {
Serial.println("[Connected]");
contMqtt = 0;
} else {
Serial.print("[Failed Connection]...");
Serial.println(clientPub.state());
delay(2000);
}
clientPub.loop();
}
void verification() {
if (!clientPub.connected()) {
Serial.println("Mqtt.....[Failed Connection]");
if (clientPub.connect("Arduinoclient", mqttUser, mqttPassword)) {
clientPub.subscribe(mqttTopic);
Serial.println("Mqtt.....[Connected]");
}
}
else {
clientPub.loop();
}
}