Doesn't reconnect to wifi unless I connect to a computer and start an IDE terminal!

Hi. I have an arduino mega 2560. I have programmed it to do various functions (3 sensors and 2 relays) and everything is workings fine (temps, distance readings, relay management, etc).

But... when there is a lost in the connection, for example when there is a power failure at home... the arduino doesn't reconnect, not to wifi (not to mqtt server). BUT IT DOESN'T RECONNECT EVEN IF I UNPLUG AND RE-PLUG IT IN!.... :open_mouth:

Let me explain fisrt that it connects to wifi with an ESP01 board hanging. And that it is powered by an USB cable connected to a 5V wall socket.

But the really strange behaivour to me is that if I unplug wait and reconnect to the 5V power, it doesn't come back... BUT! If I connect it to a computer usb, and then open arduino IDE, and then open a terminal... THEN!!!, and only THEN!!!... is reconnecting correctly again. Once is reconnected, I can close the terminal, unplug from the computer walk away (arduino unpowered), and plug it in again to the wall socket, and starts perfectly, until next hang in which I loose contact and need to reconnect it to a computer and open TERMINAL, and only then, it resets some way that starts working on again. Does that make sense?.

How could the serial terminal when opened, be doing a proper 'reset', that a powerOFF/powerON is not making?.

Let me tell you that I haven't studied programming, just doing it as a hobby, so my code could be very very ugly (and wrong). I have done it reading here and there to achieve my goals with wifi and sensors, etc, and I have to say that... when it is connected to wifi and mqtt, everyhing is working smooth...

Here is the code. I thought first about reducing the extra lines without interest, but putting it complete, could be a better way of seeing if something can cause this behaiviour.



//***************************************
//******   LIBRERIAS DEL WIFI    ********
//***************************************
#include <WiFiEspAT.h>

//***************************************
//******   LIBRERIAS DEL MQTT    ********
//***************************************
#include <PubSubClient.h>



//****************************************
//******   LIBRERIAS DEL DHT22    ********
//****************************************
// DHT22: Include the libraries
#include <Adafruit_Sensor.h>
#include <DHT.h>

//****************************************************************
//******   LIBRERIAS DEL MAX31865 (pt100 temp tuberia)    ********
//****************************************************************
#include <Adafruit_MAX31865.h>




//****************************************
//******   VARIABLES DEL DHT22    ********
//****************************************
//AQUI DEFINO LOS TOPICS PARA EL DHT22:
#define dht22TopicTemp "/arduino/dht22temperatura"
#define dht22TopicHume "/arduino/dht22humedad"

// DHT22: Set DHT pin
#define DHTPIN 2
// DHT22: Set DHT type
#define DHTTYPE DHT22   // DHT 22  (AM2302)
// DHT22: Initialize DHT sensor for normal 16mhz Arduino:
DHT dht = DHT(DHTPIN, DHTTYPE);


//*************************************************************
//******   VARIABLES PT100 (MAX31865) (temp tuberia)    *******
//*************************************************************
Adafruit_MAX31865 thermo = Adafruit_MAX31865(10, 11, 12, 13);

// The value of the Rref resistor. Use 430.0 for PT100 and 4300.0 for PT1000
#define RREF      430.0
// The 'nominal' 0-degrees-C resistance of the sensor
// 100.0 for PT100, 1000.0 for PT1000
#define RNOMINAL  100.0

// VARIABLES DE MILLIS PARA PAUSAS ENTRE CHEQUEOS DEL PT100 (temp tuberia):
unsigned long startMillisPT100;  //some global variables available anywhere in the program
unsigned long currentMillisPT100;
//Y CREO OTRA VARIABLE ESPECIFICA PARA EL INTERVALO DE LECTURAS DEL SENSOR PT100 TEMPERATURA DE TUBERIA (max31865):
const unsigned long pausaPT100 = 45000;  //45 secons pause between temp checks

// DEFINE TOPIC TO SAVE PT100 TEMP
#define pt100TopicTemp "/arduino/pt100temperatura"









//*****************************************************************************
//******   VARIABLES JSN-SR04T (ultrasonic distance waterproof)    ********
//*****************************************************************************
//DEFINO LOS pines digitales trigger y echo en la mega2560:
#define trigPin 3
#define echoPin 4

//VARIABLES duration (tiempo entre trigger y echo) y distance (guarda la distancia calculada):
long duracion;
int distancia;

// VARIABLES DE MILLIS PARA PAUSAS ENTRE CHEQUEO DE SENSOR ULTRASONIDOS (distancia):
unsigned long startMillisUltrasonidos;  //some global variables available anywhere in the program
unsigned long currentMillisUltrasonidos;
//CREO UNA VARIABLES ESPECIFICA PARA LA PAUSA ENTRE LECTURAS DEL SENSOR ULTRASONICO DE DISTANCIA WATERPROOF:
const unsigned long pausaUltrasonica = 30000;  //30 segundos para la pausa entre chequeos de distancia

//DEFINE MQTT TOPIC TO SAVE ULTRASONIC DISTANCE:
#define ultrasonicoTopic "/arduino/ultrasonicodistancia"





//***************************************
//******   VARIABLES DEL WIFI    ********
//***************************************
const char* ssid = "my_ssid";
const char* password =  "my_password";



int status = WL_IDLE_STATUS;                     // the Wifi radio's status



//***************************************************
//******   VARIABLES DEL MQTT DE LOS RELES   ********
//***************************************************

// Set led variables to Arduino digital pins
const int switchPin22 = 22;
const int switchPin23 = 23;
const int switchPin24 = 24;
const int switchPin25 = 25;
const int switchPin26 = 26;
const int switchPin27 = 27;
const int switchPin28 = 28;
const int switchPin29 = 29;
const int switchPin30 = 30;
const int switchPin31 = 31;
const int switchPin32 = 32;
const int switchPin33 = 33;
const int switchPin34 = 34;
const int switchPin35 = 35;
const int switchPin36 = 36;
const int switchPin37 = 37;
const int switchPin38 = 38;
//const int switchPin39 = 39; //SIN USO POR AHORA (CABLE MARRON), RELE OCTAVO DE LA PLACA RELE8
const int switchPin40 = 40;
const int switchPin41 = 41;
const int switchPin42 = 42;
const int switchPin43 = 43;
const int switchPin44 = 44;
const int switchPin45 = 45;



//EJ: These are the MQTT Topic that will be used to manage the state of Relays

char const* switchTopic22 = "/arduino/switch22";
char const* switchTopic23 = "/arduino/switch23";
char const* switchTopic24 = "/arduino/switch24";
char const* switchTopic25 = "/arduino/switch25";
char const* switchTopic26 = "/arduino/switch26";
char const* switchTopic27 = "/arduino/switch27";
char const* switchTopic28 = "/arduino/switch28";
char const* switchTopic29 = "/arduino/switch29";
char const* switchTopic30 = "/arduino/switch30";
char const* switchTopic31 = "/arduino/switch31";
char const* switchTopic32 = "/arduino/switch32";
char const* switchTopic33 = "/arduino/switch33";
char const* switchTopic34 = "/arduino/switch34";
char const* switchTopic35 = "/arduino/switch35";
char const* switchTopic36 = "/arduino/switch36";
char const* switchTopic37 = "/arduino/switch37";
char const* switchTopic38 = "/arduino/switch38";
//char const* switchTopic39 = "/arduino/switch39"; // //SIN USO POR AHORA (CABLE MARRON), RELE OCTAVO DE LA PLACA RELE8
char const* switchTopic40 = "/arduino/switch40";
char const* switchTopic41 = "/arduino/switch41";
char const* switchTopic42 = "/arduino/switch42";
char const* switchTopic43 = "/arduino/switch43";
char const* switchTopic44 = "/arduino/switch44";
char const* switchTopic45 = "/arduino/switch45";
//(50-53 SON DE LA ETHERNET-SHIELD, NO USAR)








//*******************************************
//******   MORE WIFI VARIABLES
//*******************************************

IPAddress ip(192, 168, 1, 159); // arduino IP in lan
IPAddress gateway(192, 168, 1, 2);




//*******************************************
//******   MAS VARIABLES DEL MQTT    ********
//*******************************************
// IP Address of your MQTT broker - change to adapt to your network
byte mqtt_server[] = { 192, 168, 1, 193 };    //direccion de Hassio







// Handle and convert incoming MQTT messages ----------------------------------------
void callback(char* topic, byte* payload, unsigned int length);


// initialize the library instance:
WiFiClient clienteWifi;
PubSubClient mqttClient(mqtt_server, 1883, callback, clienteWifi);




void setup() {

  //*******************************
  //******   SETUP PINES   ********
  //*******************************

  //initialize the switch as an output and set to HIGH (off)
  //nota: de lo leido aqui: https://forum.arduino.cc/t/relay-module-is-active-low-how-to-reverse-that/264868/45
  //poner primero el high y luego declarar el output para evitar jolgorio al bootear:

  digitalWrite(switchPin22, HIGH);
  pinMode(switchPin22, OUTPUT); // Relay 15

  digitalWrite(switchPin23, HIGH);
  pinMode(switchPin23, OUTPUT); // Relay 16

  digitalWrite(switchPin24, HIGH);
  pinMode(switchPin24, OUTPUT); // Relay 13

  digitalWrite(switchPin25, HIGH);
  pinMode(switchPin25, OUTPUT); // Relay 14

  digitalWrite(switchPin26, HIGH);
  pinMode(switchPin26, OUTPUT); // Relay 11

  digitalWrite(switchPin27, HIGH);
  pinMode(switchPin27, OUTPUT); // Relay 12

  digitalWrite(switchPin28, HIGH);
  pinMode(switchPin28, OUTPUT); // Relay 9

  digitalWrite(switchPin29, HIGH);
  pinMode(switchPin29, OUTPUT); // Relay 10

  digitalWrite(switchPin30, HIGH);
  pinMode(switchPin30, OUTPUT); // Relay 7

  digitalWrite(switchPin31, HIGH);
  pinMode(switchPin31, OUTPUT); // Relay 8

  digitalWrite(switchPin32, HIGH);
  pinMode(switchPin32, OUTPUT); // Relay 5

  digitalWrite(switchPin33, HIGH);
  pinMode(switchPin33, OUTPUT); // Relay 6

  digitalWrite(switchPin34, HIGH);
  pinMode(switchPin34, OUTPUT); // Relay 3

  digitalWrite(switchPin35, HIGH);
  pinMode(switchPin35, OUTPUT); // Relay 4

  digitalWrite(switchPin36, HIGH);
  pinMode(switchPin36, OUTPUT); // Relay 1

  digitalWrite(switchPin37, HIGH);
  pinMode(switchPin37, OUTPUT); // Relay 2

  digitalWrite(switchPin38, HIGH);
  pinMode(switchPin38, OUTPUT); // Relay-B 1

  digitalWrite(switchPin40, HIGH);
  pinMode(switchPin40, OUTPUT); // Relay-B 2

  digitalWrite(switchPin41, HIGH);
  pinMode(switchPin41, OUTPUT); // Relay-B 7

  digitalWrite(switchPin42, HIGH);
  pinMode(switchPin42, OUTPUT); // Relay-B 3

  digitalWrite(switchPin43, HIGH);
  pinMode(switchPin43, OUTPUT); // Relay-B 6

  digitalWrite(switchPin44, HIGH);
  pinMode(switchPin44, OUTPUT); // Relay-B 4

  digitalWrite(switchPin45, HIGH);
  pinMode(switchPin45, OUTPUT); // Relay-B 5


  //wait a bit before starting the main loop
  delay(1000);


  //********************************
  //******   SETUP DHT22    ********
  //********************************
  // Setup sensor TEMP_y_HUMEDAD DHT22:
  dht.begin();



  //********************************************************
  //******   SETUP PT100 MAX31865 (temp tuberia)    ********
  //********************************************************
  thermo.begin(MAX31865_3WIRE);  // set to 2WIRE or 4WIRE as necessary



  //************************************************
  //******   SETUP ULTRASONIC WATERPROOF    ********
  //************************************************
  // set trigPin as OUTPUT and echopin as INPUT:
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);



  //**********************************
  //******   NETWORK SETUP    ********
  //**********************************

  // start serial port:
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect. Needed for native USB port only

  // CONFIGURACION WIFI:
  Serial1.begin(115200);
  WiFi.init(Serial1);


  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println();
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  // disconnect persistent connection (not persistent)
  WiFi.disconnect();

  // to disable default automatic start of persistent AP at startup
  WiFi.endAP();

  Serial.println();
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);

  //  use following lines if you want to connect with bssid
  //  const byte bssid[] = {0x8A, 0x2F, 0xC3, 0xE9, 0x25, 0xC0};
  //  int status = WiFi.begin(ssid, password, bssid);

  int status = WiFi.begin(ssid, password);

  if (status == WL_CONNECTED) {
    Serial.println();
    Serial.println("Connected to WiFi network.");
    printWifiStatus();
  } else {
    WiFi.disconnect(); // remove the WiFi connection
    Serial.println();
    Serial.println("Connection to WiFi network failed.");
  }








  //*******************************
  //******   SETUP MQTT    ********
  //*******************************

  if (mqttClient.connect("mega2560", "usuario_mqtt", "my_mqtt_password")) {  //EJ: Update accordingly with your MQTT account
    mqttClient.publish("arduino", "hello world from mega2560");
    Serial.println("MQTT conectado");
    mqttClient.subscribe(switchTopic22);
    mqttClient.subscribe(switchTopic23);
    mqttClient.subscribe(switchTopic24);
    mqttClient.subscribe(switchTopic25);
    mqttClient.subscribe(switchTopic26);
    mqttClient.subscribe(switchTopic27);
    mqttClient.subscribe(switchTopic28);
    mqttClient.subscribe(switchTopic29);
    mqttClient.subscribe(switchTopic30);
    mqttClient.subscribe(switchTopic31);
    mqttClient.subscribe(switchTopic32);
    mqttClient.subscribe(switchTopic33);
    mqttClient.subscribe(switchTopic34);
    mqttClient.subscribe(switchTopic35);
    mqttClient.subscribe(switchTopic36);
    mqttClient.subscribe(switchTopic37);
    mqttClient.subscribe(switchTopic38);
    //    mqttClient.subscribe(switchTopic39); //SIN USO POR AHORA
    mqttClient.subscribe(switchTopic40);
    mqttClient.subscribe(switchTopic41);
    mqttClient.subscribe(switchTopic42);
    mqttClient.subscribe(switchTopic43);
    mqttClient.subscribe(switchTopic44);
    mqttClient.subscribe(switchTopic45);

    // Me apunto a los topics de dht22:
    mqttClient.subscribe(dht22TopicTemp);
    mqttClient.subscribe(dht22TopicHume);

    // Me apunto al topic del sensor ultrasonico:
    mqttClient.subscribe(ultrasonicoTopic);

    // Me apunto al topic de pt100 temp tuberia:
    mqttClient.subscribe(pt100TopicTemp);

  }




  //****************************************
  //******   SETUP GLOBAL MILLIs    ********
  //****************************************
  //Graba en variables el momento del arranque para comenzar a chequear periodos entre lecturas para dispositivos:
  startMillisUltrasonidos = millis();  //initial start time
  startMillisPT100 = millis();  //initial start time


} // FINAL DEL VOID SETUP





//dht22 SENSOR. CHECKS IF TEMP OR HUMIDITY CHANGED MORE THAN 0.1 AND REPUBLISH:
bool checkBound(float newValue, float prevValue, float maxDiff) {
  return !isnan(newValue) &&
         (newValue < prevValue - maxDiff || newValue > prevValue + maxDiff);
}

long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 0.1;





//*********************************
//******   LOOP  FUNCTION  ********
//*********************************
void loop() {


  //******   CHEQUEA IF MQTT IS STILL ALIVE    ********
  if (!mqttClient.connected()) {
    reconnectMqtt();
  }

  //maintain MQTT connection
  mqttClient.loop();


  //*******************************
  //******   LOOP DHT22    ********
  //*******************************

  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;

    float newTemp = dht.readTemperature();
    float newHum = dht.readHumidity();

    if (checkBound(newTemp, temp, diff)) {
      temp = newTemp;
      Serial.print("DHT22 Temperatura: ");
      Serial.println(String(temp).c_str());
      mqttClient.publish(dht22TopicTemp, String(temp).c_str(), true);
    }

    if (checkBound(newHum, hum, diff)) {
      hum = newHum;
      Serial.print("DHT22 Humedad: ");
      Serial.println(String(hum).c_str());
      mqttClient.publish(dht22TopicHume, String(hum).c_str(), true);
    }
  } //final del loop dht22




  //***************************************************************************************
  //******   LOOP ULTRASONIC: CHECK IF IT IS TIME TO START tareaUltrasonica    ************
  //***************************************************************************************
  currentMillisUltrasonidos = millis();  //get the current "time" (actually the number of milliseconds since the program started)
  // ULTRASONIDOS (distancia) SI TRANSCURRE EL PERIODO DEFINIDO PARA ULTRASONIDOS, EJECUTA LA FUNCION tareaUltrasonica:
  if (currentMillisUltrasonidos - startMillisUltrasonidos >= pausaUltrasonica)  //chequea si el periodo pausaUltrasonica (30s) ya ha transcurrido...
  {
    tareaUltrasonica(); // Si se cumple el periodo, llama a la funcion de tareas del tareaUltrasonica definida mas abajo.
    startMillisUltrasonidos = currentMillisUltrasonidos;  //IMPORTANT to save the start time of the current state.
  }


  //****************************************************************************
  //******   LOOP PT100: COMPRUEBA SI ES HORA DE EJECUTAR tareaPT100    ********
  //****************************************************************************
  currentMillisPT100 = millis();  //get the current "time" (actually the number of milliseconds since the program started)
  // PT100: SI TRANSCURRE EL PERIODO DEFINIDO PARA temp tuberia pt100, EJECUTA LA FUNCION tareaPT100:
  if (currentMillisPT100 - startMillisPT100 >= pausaPT100)  //chequea si el periodo pausaPT100 (45s) ya ha transcurrido...
  {
    tareaPT100();    // Hago que tambien lea la temp de pt100 (tuberia)
    startMillisPT100 = currentMillisPT100;  //IMPORTANT to save the start time of the current state.
  }


} //FINAL DEL LOOP




//**********************************************
//******   FUNCION PRINT WIFI STATUS    ********
//**********************************************
void printWifiStatus() {

  // print the SSID of the network you're attached to:
  char ssid[33];
  WiFi.SSID(ssid);
  Serial.print("SSID: ");
  Serial.println(ssid);

  // print the BSSID of the network you're attached to:
  uint8_t bssid[6];
  WiFi.BSSID(bssid);
  Serial.print("BSSID: ");
  printMacAddress(bssid);

  uint8_t mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC: ");
  printMacAddress(mac);

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}








//**********************************************
//******   FUNCION PRINT MAC ADDRESS    ********
//**********************************************
void printMacAddress(byte mac[]) {
  for (int i = 5; i >= 0; i--) {
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
    if (i > 0) {
      Serial.print(":");
    }
  }
  Serial.println();
}









//*************************************
//******   FUNCION CALLBACK    ********
//*************************************
//print any message received for subscribed topic
void callback(char* topic, byte* payload, unsigned int length) {

  //convert topic to string to make it easier to work with
  String topicStr = topic;
  //EJ: Note:  the "topic" value gets overwritten everytime it receives confirmation (callback) message from MQTT

  //Print out some debugging info
  Serial.print("Topic: ");
  Serial.println(topicStr);


  //PIN22
  if (topicStr == "/arduino/switch22")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin22, LOW);
      mqttClient.publish("/arduino/switchConfirm22", "1");
      if (digitalRead(22) == LOW) {
        Serial.print("Valor pin 22: ON\n");
      }
      if (digitalRead(22) == HIGH) {
        Serial.print("Valor pin 22: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin22, HIGH);
      mqttClient.publish("/arduino/switchConfirm22", "0");
      if (digitalRead(22) == LOW) {
        Serial.print("Valor pin 22: ON\n");
      }
      if (digitalRead(22) == HIGH) {
        Serial.print("Valor pin 22: OFF\n");
      }
    }
  }

  //PIN23
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch23")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin23, LOW);
      mqttClient.publish("/arduino/switchConfirm23", "1");
      if (digitalRead(23) == LOW) {
        Serial.print("Valor pin 23: ON\n");
      }
      if (digitalRead(23) == HIGH) {
        Serial.print("Valor pin 23: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin23, HIGH);
      mqttClient.publish("/arduino/switchConfirm23", "0");
      if (digitalRead(23) == LOW) {
        Serial.print("Valor pin 23: ON\n");
      }
      if (digitalRead(23) == HIGH) {
        Serial.print("Valor pin 23: OFF\n");
      }
    }
  }

  //PIN24
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch24")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin24, LOW);
      mqttClient.publish("/arduino/switchConfirm24", "1");
      if (digitalRead(24) == LOW) {
        Serial.print("Valor pin 24: ON\n");
      }
      if (digitalRead(24) == HIGH) {
        Serial.print("Valor pin 24: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin24, HIGH);
      mqttClient.publish("/arduino/switchConfirm24", "0");
      if (digitalRead(24) == LOW) {
        Serial.print("Valor pin 24: ON\n");
      }
      if (digitalRead(24) == HIGH) {
        Serial.print("Valor pin 24: OFF\n");
      }
    }
  }

  //PIN25
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch25")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin25, LOW);
      mqttClient.publish("/arduino/switchConfirm25", "1");
      if (digitalRead(25) == LOW) {
        Serial.print("Valor pin 25: ON\n");
      }
      if (digitalRead(25) == HIGH) {
        Serial.print("Valor pin 25: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin25, HIGH);
      mqttClient.publish("/arduino/switchConfirm25", "0");
      if (digitalRead(25) == LOW) {
        Serial.print("Valor pin 25: ON\n");
      }
      if (digitalRead(25) == HIGH) {
        Serial.print("Valor pin 25: OFF\n");
      }
    }
  }

  //PIN26
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch26")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin26, LOW);
      mqttClient.publish("/arduino/switchConfirm26", "1");
      if (digitalRead(26) == LOW) {
        Serial.print("Valor pin 26: ON\n");
      }
      if (digitalRead(26) == HIGH) {
        Serial.print("Valor pin 26: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin26, HIGH);
      mqttClient.publish("/arduino/switchConfirm26", "0");
      if (digitalRead(26) == LOW) {
        Serial.print("Valor pin 26: ON\n");
      }
      if (digitalRead(26) == HIGH) {
        Serial.print("Valor pin 26: OFF\n");
      }
    }
  }

  //PIN27
  else if (topicStr == "/arduino/switch27")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin27, LOW);
      mqttClient.publish("/arduino/switchConfirm27", "1");
      if (digitalRead(27) == LOW) {
        Serial.print("Valor pin 27: ON\n");
      }
      if (digitalRead(27) == HIGH) {
        Serial.print("Valor pin 27: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin27, HIGH);
      mqttClient.publish("/arduino/switchConfirm27", "0");
      if (digitalRead(27) == LOW) {
        Serial.print("Valor pin 27: ON\n");
      }
      if (digitalRead(27) == HIGH) {
        Serial.print("Valor pin 27: OFF\n");
      }
    }
  }

  //PIN28
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch28")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin28, LOW);
      mqttClient.publish("/arduino/switchConfirm28", "1");
      if (digitalRead(28) == LOW) {
        Serial.print("Valor pin 28: ON\n");
      }
      if (digitalRead(28) == HIGH) {
        Serial.print("Valor pin 28: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin28, HIGH);
      mqttClient.publish("/arduino/switchConfirm28", "0");
      if (digitalRead(28) == LOW) {
        Serial.print("Valor pin 28: ON\n");
      }
      if (digitalRead(28) == HIGH) {
        Serial.print("Valor pin 28: OFF\n");
      }
    }
  }

  //PIN29
  else if (topicStr == "/arduino/switch29")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin29, LOW);
      mqttClient.publish("/arduino/switchConfirm29", "1");
      if (digitalRead(29) == LOW) {
        Serial.print("Valor pin 29: ON\n");
      }
      if (digitalRead(29) == HIGH) {
        Serial.print("Valor pin 29: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin29, HIGH);
      mqttClient.publish("/arduino/switchConfirm29", "0");
      if (digitalRead(29) == LOW) {
        Serial.print("Valor pin 29: ON\n");
      }
      if (digitalRead(29) == HIGH) {
        Serial.print("Valor pin 29: OFF\n");
      }
    }
  }

  //PIN30
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch30")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin30, LOW);
      mqttClient.publish("/arduino/switchConfirm30", "1");
      if (digitalRead(30) == LOW) {
        Serial.print("Valor pin 30: ON\n");
      }
      if (digitalRead(30) == HIGH) {
        Serial.print("Valor pin 30: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin30, HIGH);
      mqttClient.publish("/arduino/switchConfirm30", "0");
      if (digitalRead(30) == LOW) {
        Serial.print("Valor pin 30: ON\n");
      }
      if (digitalRead(30) == HIGH) {
        Serial.print("Valor pin 30: OFF\n");
      }
    }
  }

  //PIN31
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch31")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin31, LOW);
      mqttClient.publish("/arduino/switchConfirm31", "1");
      if (digitalRead(31) == LOW) {
        Serial.print("Valor pin 31: ON\n");
      }
      if (digitalRead(31) == HIGH) {
        Serial.print("Valor pin 31: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin31, HIGH);
      mqttClient.publish("/arduino/switchConfirm31", "0");
      if (digitalRead(31) == LOW) {
        Serial.print("Valor pin 31: ON\n");
      }
      if (digitalRead(31) == HIGH) {
        Serial.print("Valor pin 31: OFF\n");
      }
    }
  }

  //PIN32
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch32")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin32, LOW);
      mqttClient.publish("/arduino/switchConfirm32", "1");
      if (digitalRead(32) == LOW) {
        Serial.print("Valor pin 32: ON\n");
      }
      if (digitalRead(32) == HIGH) {
        Serial.print("Valor pin 32: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin32, HIGH);
      mqttClient.publish("/arduino/switchConfirm32", "0");
      if (digitalRead(32) == LOW) {
        Serial.print("Valor pin 32: ON\n");
      }
      if (digitalRead(32) == HIGH) {
        Serial.print("Valor pin 32: OFF\n");
      }
    }
  }

  //PIN33
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch33")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin33, LOW);
      mqttClient.publish("/arduino/switchConfirm33", "1");
      if (digitalRead(33) == LOW) {
        Serial.print("Valor pin 33: ON\n");
      }
      if (digitalRead(33) == HIGH) {
        Serial.print("Valor pin 33: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin33, HIGH);
      mqttClient.publish("/arduino/switchConfirm33", "0");
      if (digitalRead(33) == LOW) {
        Serial.print("Valor pin 33: ON\n");
      }
      if (digitalRead(33) == HIGH) {
        Serial.print("Valor pin 33: OFF\n");
      }
    }
  }

  //PIN34
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch34")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin34, LOW);
      mqttClient.publish("/arduino/switchConfirm34", "1");
      if (digitalRead(34) == LOW) {
        Serial.print("Valor pin 34: ON\n");
      }
      if (digitalRead(34) == HIGH) {
        Serial.print("Valor pin 34: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin34, HIGH);
      mqttClient.publish("/arduino/switchConfirm34", "0");
      if (digitalRead(34) == LOW) {
        Serial.print("Valor pin 34: ON\n");
      }
      if (digitalRead(34) == HIGH) {
        Serial.print("Valor pin 34: OFF\n");
      }
    }
  }

  //PIN35
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch35")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin35, LOW);
      mqttClient.publish("/arduino/switchConfirm35", "1");
      if (digitalRead(35) == LOW) {
        Serial.print("Valor pin 35: ON\n");
      }
      if (digitalRead(35) == HIGH) {
        Serial.print("Valor pin 35: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin35, HIGH);
      mqttClient.publish("/arduino/switchConfirm35", "0");
      if (digitalRead(35) == LOW) {
        Serial.print("Valor pin 35: ON\n");
      }
      if (digitalRead(35) == HIGH) {
        Serial.print("Valor pin 35: OFF\n");
      }
    }
  }

  //PIN36
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch36")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin36, LOW);
      mqttClient.publish("/arduino/switchConfirm36", "1");
      if (digitalRead(36) == LOW) {
        Serial.print("Valor pin 36: ON\n");
      }
      if (digitalRead(36) == HIGH) {
        Serial.print("Valor pin 36: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin36, HIGH);
      mqttClient.publish("/arduino/switchConfirm36", "0");
      if (digitalRead(36) == LOW) {
        Serial.print("Valor pin 36: ON\n");
      }
      if (digitalRead(36) == HIGH) {
        Serial.print("Valor pin 36: OFF\n");
      }
    }
  }

  //PIN37
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch37")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin37, LOW);
      mqttClient.publish("/arduino/switchConfirm37", "1");
      if (digitalRead(37) == LOW) {
        Serial.print("Valor pin 37: ON\n");
      }
      if (digitalRead(37) == HIGH) {
        Serial.print("Valor pin 37: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin37, HIGH);
      mqttClient.publish("/arduino/switchConfirm37", "0");
      if (digitalRead(37) == LOW) {
        Serial.print("Valor pin 37: ON\n");
      }
      if (digitalRead(37) == HIGH) {
        Serial.print("Valor pin 37: OFF\n");
      }
    }
  }

  //PIN38
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch38")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin38, LOW);
      mqttClient.publish("/arduino/switchConfirm38", "1");
      if (digitalRead(38) == LOW) {
        Serial.print("Valor pin 38: ON\n");
      }
      if (digitalRead(38) == HIGH) {
        Serial.print("Valor pin 38: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin38, HIGH);
      mqttClient.publish("/arduino/switchConfirm38", "0");
      if (digitalRead(38) == LOW) {
        Serial.print("Valor pin 38: ON\n");
      }
      if (digitalRead(38) == HIGH) {
        Serial.print("Valor pin 38: OFF\n");
      }
    }
  }

  //DESACTIVO PORQUE ES PIN Y RELE SIN USO POR AHORA (RELE8 DE RELE8, CABLE MARRON, YA CONECTADO)
  ////PIN39
  //     // EJ: copy and paste this whole else-if block, should you need to control more switches
  //     else if (topicStr == "/arduino/switch39")
  //     {
  //     //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
  //     if(payload[0] == '1'){
  //       digitalWrite(switchPin39, LOW);
  //       mqttClient.publish("/arduino/switchConfirm39", "1");
  //       if (digitalRead(39)==LOW) { Serial.print("Valor pin 39: ON\n"); }
  //       if (digitalRead(39)==HIGH) { Serial.print("Valor pin 39: OFF\n"); }
  //       }
  //
  //      //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
  //     else if (payload[0] == '0'){
  //       digitalWrite(switchPin39, HIGH);
  //       mqttClient.publish("/arduino/switchConfirm39", "0");
  //       if (digitalRead(39)==LOW) { Serial.print("Valor pin 39: ON\n"); }
  //       if (digitalRead(39)==HIGH) { Serial.print("Valor pin 39: OFF\n"); }
  //       }
  //     }

  //PIN40
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch40")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin40, LOW);
      mqttClient.publish("/arduino/switchConfirm40", "1");
      if (digitalRead(40) == LOW) {
        Serial.print("Valor pin 40: ON\n");
      }
      if (digitalRead(40) == HIGH) {
        Serial.print("Valor pin 40: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin40, HIGH);
      mqttClient.publish("/arduino/switchConfirm40", "0");
      if (digitalRead(40) == LOW) {
        Serial.print("Valor pin 40: ON\n");
      }
      if (digitalRead(40) == HIGH) {
        Serial.print("Valor pin 40: OFF\n");
      }
    }
  }

  //PIN41
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch41")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin41, LOW);
      mqttClient.publish("/arduino/switchConfirm41", "1");
      if (digitalRead(41) == LOW) {
        Serial.print("Valor pin 41: ON\n");
      }
      if (digitalRead(41) == HIGH) {
        Serial.print("Valor pin 41: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin41, HIGH);
      mqttClient.publish("/arduino/switchConfirm41", "0");
      if (digitalRead(41) == LOW) {
        Serial.print("Valor pin 41: ON\n");
      }
      if (digitalRead(41) == HIGH) {
        Serial.print("Valor pin 41: OFF\n");
      }
    }
  }

  //PIN42
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch42")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin42, LOW);
      mqttClient.publish("/arduino/switchConfirm42", "1");
      if (digitalRead(42) == LOW) {
        Serial.print("Valor pin 42: ON\n");
      }
      if (digitalRead(42) == HIGH) {
        Serial.print("Valor pin 42: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin42, HIGH);
      mqttClient.publish("/arduino/switchConfirm42", "0");
      if (digitalRead(42) == LOW) {
        Serial.print("Valor pin 42: ON\n");
      }
      if (digitalRead(42) == HIGH) {
        Serial.print("Valor pin 42: OFF\n");
      }
    }
  }

  //PIN43
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch43")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin43, LOW);
      mqttClient.publish("/arduino/switchConfirm43", "1");
      if (digitalRead(43) == LOW) {
        Serial.print("Valor pin 43: ON\n");
      }
      if (digitalRead(43) == HIGH) {
        Serial.print("Valor pin 43: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin43, HIGH);
      mqttClient.publish("/arduino/switchConfirm43", "0");
      if (digitalRead(43) == LOW) {
        Serial.print("Valor pin 43: ON\n");
      }
      if (digitalRead(43) == HIGH) {
        Serial.print("Valor pin 43: OFF\n");
      }
    }
  }

  //PIN44
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch44")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin44, LOW);
      mqttClient.publish("/arduino/switchConfirm44", "1");
      if (digitalRead(44) == LOW) {
        Serial.print("Valor pin 44: ON\n");
      }
      if (digitalRead(44) == HIGH) {
        Serial.print("Valor pin 44: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin44, HIGH);
      mqttClient.publish("/arduino/switchConfirm44", "0");
      if (digitalRead(44) == LOW) {
        Serial.print("Valor pin 44: ON\n");
      }
      if (digitalRead(44) == HIGH) {
        Serial.print("Valor pin 44: OFF\n");
      }
    }
  }

  //PIN45
  // EJ: copy and paste this whole else-if block, should you need to control more switches
  else if (topicStr == "/arduino/switch45")
  {
    //turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
    if (payload[0] == '1') {
      digitalWrite(switchPin45, LOW);
      mqttClient.publish("/arduino/switchConfirm45", "1");
      if (digitalRead(45) == LOW) {
        Serial.print("Valor pin 45: ON\n");
      }
      if (digitalRead(45) == HIGH) {
        Serial.print("Valor pin 45: OFF\n");
      }
    }

    //turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0') {
      digitalWrite(switchPin45, HIGH);
      mqttClient.publish("/arduino/switchConfirm45", "0");
      if (digitalRead(45) == LOW) {
        Serial.print("Valor pin 45: ON\n");
      }
      if (digitalRead(45) == HIGH) {
        Serial.print("Valor pin 45: OFF\n");
      }
    }
  }



}  // FINAL DE FUNCION VOID CALLBACK








//*******************************************************
//******   FUNCION RECONNECTMQTT (check mqtt)    ********
//*******************************************************
// FUNCIONES DE CHEQUEO Y RECONEXION DE MQTT SI SE PIERDE CONEXION CON MQTT SERVER:
// Reconecta si pierde conexion con el servidor MQTT (HA) -----------------------------------
void reconnectMqtt() {
  // Loop until we're reconnected al servidor mqtt:
  while (!mqttClient.connected()) {
    Serial.print("Trying to connect to MQTT...");

    // Attempt to connect
    if (mqttClient.connect("mega2560", "usuario_mqtt", "my_mqtt_password")) {
      mqttClient.publish("arduino", "hello world - AGAIN mega2560");
      Serial.println("\nMQTT RE-connected\n");
      // Subscribe or resubscribe to a topic
      // You can subscribe to more topics (to control more outputs)
      mqttClient.subscribe(switchTopic22);
      mqttClient.subscribe(switchTopic23);
      mqttClient.subscribe(switchTopic24);
      mqttClient.subscribe(switchTopic25);
      mqttClient.subscribe(switchTopic26);
      mqttClient.subscribe(switchTopic27);
      mqttClient.subscribe(switchTopic28);
      mqttClient.subscribe(switchTopic29);
      mqttClient.subscribe(switchTopic30);
      mqttClient.subscribe(switchTopic31);
      mqttClient.subscribe(switchTopic32);
      mqttClient.subscribe(switchTopic33);
      mqttClient.subscribe(switchTopic34);
      mqttClient.subscribe(switchTopic35);
      mqttClient.subscribe(switchTopic36);
      mqttClient.subscribe(switchTopic37);
      mqttClient.subscribe(switchTopic38);
      //    mqttClient.subscribe(switchTopic39); // SIN USO POR AHORA
      mqttClient.subscribe(switchTopic40);
      mqttClient.subscribe(switchTopic41);
      mqttClient.subscribe(switchTopic42);
      mqttClient.subscribe(switchTopic43);
      mqttClient.subscribe(switchTopic44);
      mqttClient.subscribe(switchTopic45);


      //DHT22 que se reconecte tambien a la temperatura de DHT22:
      mqttClient.subscribe(dht22TopicTemp);
      mqttClient.subscribe(dht22TopicHume);

      //ULTRASONICO, que se reconecte tambien al topic de distancia:
      mqttClient.subscribe(ultrasonicoTopic);

      //PT100 que se reconecte tambien a la temp tuberia del PT100 (max31865):
      mqttClient.subscribe(pt100TopicTemp);



    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      // Muestra la razon del codigo de fallo de conexion al mqtt server:
      if (mqttClient.state() == -4) {
        Serial.print("\nMQTT_CONNECTION_TIMEOUT server did not respond within the keepalive time\n");
      }
      if (mqttClient.state() == -3) {
        Serial.print("\nMQTT_CONNECTION_LOST network connection was broken\n");
      }
      if (mqttClient.state() == -2) {
        Serial.print("\nMQTT_CONNECT_FAILED network connection failed\n");
      }
      if (mqttClient.state() == -1) {
        Serial.print("\nMQTT_DISCONNECTED client is disconnected cleanly\n");
      }
      if (mqttClient.state() == 0) {
        Serial.print("\nMQTT_CONNECTED client is connected\n");
      }
      if (mqttClient.state() == 1) {
        Serial.print("\nMQTT_CONNECT_BAD_PROTOCOL server does not support the requested version of MQTT\n");
      }
      if (mqttClient.state() == 2) {
        Serial.print("\nMQTT_CONNECT_BAD_CLIENT_ID server rejected the client identifier\n");
      }
      if (mqttClient.state() == 3) {
        Serial.print("\nMQTT_CONNECT_UNAVAILABLE server was unable to accept the connection\n");
      }
      if (mqttClient.state() == 4) {
        Serial.print("\nMQTT_CONNECT_BAD_CREDENTIALS username-password were rejected\n");
      }
      if (mqttClient.state() == 4) {
        Serial.print("\nMQTT_CONNECT_UNAUTHORIZED client was not authorized to connect\n");
      }
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}  //FINAL FUNCION RECONNECT MQTT





//**********************************************************
//******   FUNCION ULTRASONIC TASK for the LOOP:    ********
//**********************************************************

void tareaUltrasonica() {

  // LIMPIA EL TRIGGER PIN PONIENDOLO EN LOW:
  digitalWrite(trigPin, LOW);
  // Y METE UNA PAUSITA (DEL TUTO):
  delayMicroseconds(5);

  // PONE DURANTE 10 MICROSEGUNDOS EL PIN TRIGGER EN HIGH:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // LEE EL PIN ECHO. pulseIn() DA LA DURACION EN MICROSEGUNDOS:
  duracion = pulseIn(echoPin, HIGH);

  // CALCULATE DISTANCE:
  distancia = duracion * 0.034 / 2;

  // PRINT DISTANCE:
  Serial.print("Distancia: ");
  Serial.print(distancia);
  Serial.println(" cm");
  // AND PUBLISH ON MQTT:
  mqttClient.publish(ultrasonicoTopic, String(distancia).c_str(), true);

  //METE OTRA MINIPAUSA:
  delay(100);


} // FIN tareaUltrasonica






//****************************************************************
//******   FUNCION TASK PT100 (max31865) for the LOOP:    ********
//****************************************************************

void tareaPT100() {
  uint16_t rtd = thermo.readRTD();

  Serial.print("PT100 RTD value: "); Serial.println(rtd);
  float ratio = rtd;
  ratio /= 32768;
  Serial.print("PT100 Ratio = "); Serial.println(ratio, 8);
  Serial.print("PT100 Resistencia = "); Serial.println(RREF * ratio, 8);

  float pt100temp = thermo.temperature(RNOMINAL, RREF);
  Serial.print("PT100 Temperatura = "); Serial.println(pt100temp);
  // Y LA PUBLICA EN EL TOPIC DE MQTT:
  mqttClient.publish(pt100TopicTemp, String(pt100temp).c_str(), true);


  // Check and print any faults
  uint8_t fault = thermo.readFault();
  if (fault) {
    Serial.print("PT100 Fault 0x"); Serial.println(fault, HEX);
    if (fault & MAX31865_FAULT_HIGHTHRESH) {
      Serial.println("PT100 RTD High Threshold");
    }
    if (fault & MAX31865_FAULT_LOWTHRESH) {
      Serial.println("PT100 RTD Low Threshold");
    }
    if (fault & MAX31865_FAULT_REFINLOW) {
      Serial.println("PT100 REFIN- > 0.85 x Bias");
    }
    if (fault & MAX31865_FAULT_REFINHIGH) {
      Serial.println("PT100 REFIN- < 0.85 x Bias - FORCE- open");
    }
    if (fault & MAX31865_FAULT_RTDINLOW) {
      Serial.println("PT100 RTDIN- < 0.85 x Bias - FORCE- open");
    }
    if (fault & MAX31865_FAULT_OVUV) {
      Serial.println("PT100 Under/Over voltage");
    }
    thermo.clearFault();
  }
  Serial.println();
  delay(1000);

} // FIN tareaMax31865




//fin

What happens if you comment out the "while (!Serial); // wait for serial port to connect. Needed for native USB port only" line.

when you reboot you are likely stuck there unless you open the serial port as documented

Ooops.... Thanks Riva and J.M.L, I'll check that tonight and let you know how it goes.

I have commented out the line.. but yes..., that has all the sense :flushed: , that it was causing the arduino to wait forever. Didn't noticed I have that line. Sorry.

The only strange thing to me is that, after plugin it to a computer and come back to life, when I then unplug it and plug it to a wall socket (no-computer)... it kept working without getting stuck, even with the 'while serial' line there..., until another power failure, etc. :-/

Anyway... I have uploaded the new code, but because I'm doing it remotely at 50 km away from the board, I will wait until tomorrow, that I will check it locally, to confirm that the problem is solved and mark it as solved.

Thanks both.

Just noticed the mention of running this on a MEGA. Then it’s not the issue.

Explain how the circuit works and is powered. ESP01 is also not a very reliable board, you should consider moving to a one board architecture with an more capable ESP (wemos D1 or ESP32 based MCU for example)

You might want to try a few times instead of only once

:frowning_face:
Yes, it's a Mega. I use serial for USB and serial1 for wifi (esp01)

nemo

...sorry, couldn't resist.

You mean connecting it to Mega, or as an stand alone solution?. If the latter, I need many more digital pins because I have to manage 24 relays and some sensors at my swimming pool. I have some esp32 and nodemcu at other places.

That made me review the WiFiEspAT library that ESP01 uses, to see how can I code the reconnects. As in the library example file: SetupPersistentWifiConnection.ino I have seen that I miss the persistent line:

  WiFi.setPersistent(); // set the following WiFi connection as persistent

As my arduino only connects to a router (next to it by the way), I can use persistent and remember the last good connection to reconnet. If I understand correcly here:

https://github.com/jandrassy/WiFiEspAT#persistent-wifi-connection

I have also changed some other lines in my sketch (edited here for only network related lines):

#include <WiFiEspAT.h>

const char* ssid = "my_ssid";
const char* password =  "my_password";


void setup() {

  // start serial port:
  Serial.begin(115200);
  delay(10);


  // WIFI CONFIG:
  Serial1.begin(115200);
  WiFi.init(Serial1);
  delay(10);


  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println();
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  // FROM THE WifiEspAT example: SetupPersistentWifiConnection.ino
  WiFi.disconnect(); // to clear the way. not persistent

  WiFi.setPersistent(); // set the following WiFi connection as persistent

  WiFi.endAP(); // to disable default automatic start of persistent AP at startup

  //  uncomment this lines for persistent static IP. set addresses valid for your network
  IPAddress ip(192, 168, 1, 159);
  IPAddress gw(192, 168, 1, 2);
  IPAddress nm(255, 255, 255, 0);
  WiFi.config(ip, gw, gw, nm);

  Serial.println();
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);

  int status = WiFi.begin(ssid, password);

  if (status == WL_CONNECTED) {
    Serial.println();
    Serial.println("Connected to WiFi network.");
    printWifiStatus();
  } else {
    WiFi.disconnect(); // remove the WiFi connection
    Serial.println();
    Serial.println("Connection to WiFi network failed.");
  }

} // END VOID SETUP


void loop() {
}


//*************************************************************
//******   FUNCION TO SHOW WIFI INFO WHEN CONNECTED    ********
//*************************************************************

void printWifiStatus() {

  // print the SSID of the network you're attached to:
  char ssid[33];
  WiFi.SSID(ssid);
  Serial.print("SSID: ");
  Serial.println(ssid);

  // print the BSSID of the network you're attached to:
  uint8_t bssid[6];
  WiFi.BSSID(bssid);
  Serial.print("BSSID: ");
  printMacAddress(bssid);

  uint8_t mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC: ");
  printMacAddress(mac);

  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}


//**********************************************
//******   FUNCION PRINT MAC ADDRESS    ********
//**********************************************
void printMacAddress(byte mac[]) {
  for (int i = 5; i >= 0; i--) {
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
    if (i > 0) {
      Serial.print(":");
    }
  }
  Serial.println();
}

It is working fine. But I have to say that previously it does the reconnect ok too, (at least when it was plugged to a computer with terminal opened). If I reboot the router, I see the arduino reconnect as soon as the router wifi becomes available again. So wifi reconnects seems fine.

I have also removed the 'while serial' line... (usb to computer keps working fine without it) in case it affects negatively. Not sure if I have fixed something, days will tell. I'll let you know how it goes with the new 'persistent' line and the 'while serial' removed.

I did mean as a stand alone solution. There are port extenders to deal with "not enough I/O" issues.

...I like your idea. I'm very confortable with esp32 or nodemcu and with esphome because all i do is for using them with Home Assistant, so... I'll think about it. If I'm not able to fix the problem with my mega, I will search for port expanders.

This reminds me that I was very surprised when I bought the mega, that it doesn't include a wifi chipset in it. I know now that there are models which does, but I have already bought mine thinking it will come with a wifi chipset in it. I was mistaken.

Edit: I have unplug the arduino from the computer and is stand alone to a wall socket. It connected nice to wifi and is giving readings from the sensors. I have been able to do that before... the key is that it keeps working and doesn't dissapear after a power outage or somehing. I will post results here... thanks.

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