Esp32 switch ethernet with w5500 to wifi

Hi, I use esp32 with a w5500 ethernet board.

So, I’am using Ethernet.h library and I’am checking first if the w5500 is connected to a router.

bool testEthernet() {
    
    esp_read_mac(mac, ESP_MAC_ETH);    //read wifi macadres 
    Ethernet.init(ETHERNET_CS_PIN);
    ethernetReset(ETHERNET_RESET_PIN);
    delay(100);
    if(Ethernet.begin(mac)){
      return true;
    }
    return false;
}

The function gives a true/false back and that is working.

If true, I make the full ethernet connection with mqtt. That is working perfect.

If false, the I like to start a wifi connection with the esp32 module.

The start function for wifi is:

void WifiDown(){

  WiFi.disconnect();
  delay(100);
  WiFi.mode(WIFI_STA); 
  WiFi.persistent(false); // Don't write Wi-Fi credentials to flash
  // Start the connection
  if (!WiFi.config(STATIC_IP, GATEWAY, SUBNET)){
    Serial.println("Setting static IP failed");
  }
  WiFi.begin(wifiSSID, wifiPassword);
}

But the esp32 restarts allways at => WiFi.mode(WIFI_STA);

So it is not possible the setup a wifi_sta mode.

If I don’t use the testEthernet() function, then there is no problem to setup a wifi network. So I think, there is something in testEthernet() set that prevents to setup the wifi connection

What do I have to add to get that working?

This makes no sense especially since your code says to set up in STA mode.

Since you said

Your best bet is to use the Examples code. Since you did not tell us what hardware or what libraries you are using (show FULL source code). Simply use the AP or STA example code in the else block of the MQTT check.

Is this not the hardware and library that you are asking for?

The esp32 and the ethernet board alone is working perfectly with mqtt.

The esp32 and the wifi connection alone is working perfectly with mqtt.

In my next programm I added a fuction testEthernet() . That is only what I added.

if true, I go to the ethernet connection like it was before, and that is still working.

If false, then I go to the wifi setup , identical like the one I made before ( what was working ) and now it is not working anymore.

So the only change from old to new program was the addition of the function testEthernet().

I think that there are some setting made in de ethernet library that I have to reset before I can start a wifi connection.

I doubt it but without seeing ALL the code impossible to know.

You failed to answer my question re AP or STA.

You failed to answer my question re what board/hardware.

Is esp32 not hardware? It is a normal 30 pins esp32 wroom. Nothing more.

I am working with different .ino

The main.ino is splitting the lan and wifi to core 0 and my program to core 1

In network.ino go to handler_wifi_mqtt(void* parameter) function and there you see the call to testEthernet() ( that I put in comment)

I addes a new if => “if (!0){ // false = Wifi of true = Lan” to simulate a testEthernet() wifi return. Then My programm with wifi is working perfectly

If I change the if to “if (!1){ // false = Wifi of true = Lan” to simulate a testEthernet() lan return. Then My programm with lan is working perfectly

Only if I let the function testEthernet() gifs the true/ false return, the wifi restarts.

main.ino:

// Als je de verkeerde Esp gebruikt geeft die een fout 
#ifndef ESP32 
  #error "This code is designed for ESP32 architecture"
#endif
 
// INCLUDES
#include <WiFi.h>
// MQTT client, see https://github.com/knolleary/pubsubclient
#include <PubSubClient.h>
// JSON serialisation, see https://arduinojson.org/
#include <ArduinoJson.h>
#include <LittleFS.h>
#include <LiquidCrystal_I2C.h> 
#include <SPI.h>
#include <Ethernet.h> 
// Ethernet mac address:
#include "esp_system.h"
#include "esp_mac.h"

// in de ethernet.h heb ik de timeout = 60000 veranderd naar timeout = 6000
// => static int begin(uint8_t *mac, unsigned long timeout = 6000, unsigned long responseTimeout = 4000);
// we moeten anders te lang wachten als we testEthernet() uitvoeren

// spel variablen en definities
#include "Speldeclaraties.h"

// wifi en mqtt instellingen voor verbinding met raspberry pi controller
#include "Wifi_Mqtt_basic.h"

LiquidCrystal_I2C lcdsetup(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
                                        // display achteraan het spel

#define BildinLed 2      // led on esp32 board
#define networkpin 14     // voor netwerk aan => GPIO 14 to Vcc en uit => GPIO 14 to Gnd

bool einde = false;                  // eindresultaat gevonden

String I2Cadr = "";                 // voor ScanI2C devices
bool I2C0x20 = false;               // pcfout
bool I2C0x21 = false;               // pcfin
bool I2C0x26 = false;               // lcdGame
bool I2C0x27 = false;               // lcdSetup
bool I2C0x40 = false;               // servo board
bool I2C0x65 = false;               // touch keypad

// Keep track of time of last wifi startup
unsigned long WifiTimeStamp; 

#define __FILENAME__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)

TaskHandle_t Task1;

//***************************************************************************
// Setup
//***************************************************************************
void setup(){
  // Initialise serial connection
  Serial.begin(115200);
  delay(100);
  Serial.println("");
  Serial.println(__FILE__);
  Serial.println(__DATE__ "  " __TIME__);
  
  pinMode(BildinLed, OUTPUT);           // interne led ON = geen wifi verbinding, OFF Wifi verbinding
  pinMode(networkpin, INPUT_PULLUP);    // network in/uit-schakelen met console werken

  digitalWrite(BildinLed, true);        // wifiled aan doen 
  state = Uit;                          // spel staat nog uit
  Serial.print("Opstarten - state = "); Serial.println(state);

  initLcdSetup();         // init Lcd display achteraan het spel 
  ScanI2C ();             // scan aanwezigheid van I2C devices

  // LcdSetup info tijdens opstart:
  writeLcdSetup("filename: ",__FILENAME__);
  writeLcdSetup("Versie: ", __DATE__);

  if (I2C0x26){            // spel met lcdgame (gedetecteerd in ScanI2C)
  Serial.println("init lcdgame ");
  initlcdgame();           // init lcdgame display vooraan het spel 
  lcdgame.backlight();
  lcdgame.setCursor(4, 0);
  lcdgame.print("Opstart");
  }

  
  lcdsetup.clear();

//***************************************************************************
// lees de networkpin value => netwerk en mqtt aan of uit
//***************************************************************************
  if(digitalRead(networkpin)){    // lezen netwerk schakelaar met/zonder console
    networkOn = Wifi;             // we kijken verder als het wifi of lan wordt
    Serial.println ("wifi/lan : netwerk");
  }
  else {
    networkOn = Geen;
    Serial.print ("wifi/lan : ");
    Serial.println(nettxt[networkOn] + " netwerk");
  }
 
  if(!readconfigFile()){  // de config file moet altijd gelezen worden, 
                          // ook al hebben we die niet nodg om zonder console te spelen
                          // staat in escapeBasic.ino
    while (true){         // geen file => blijf setup display schrijven
      writeLcdSetup("Config file","niet te vinden");   // schrijf op lcdsetup => geen config file
      writeLcdSetup("Spel kan niet", "gespeeld worden");   // schrijf op lcdsetup => spel kan niet gespeeld worden
    }
  }
  
  
  if (networkOn){ // doe dit enkel als er wifi/Lan en mqtt nodig is
    // FreeRTOS-taken starten
    xTaskCreatePinnedToCore(
    handler_wifi_mqtt,    // Functie
    "Task1",       // Naam van de taak
    10000,               // Stapelgrootte
    NULL,               // Parameter
    1,                  // Prioriteit
    NULL,               // Taakhandle
    0                   // Core 0
    );
  }
  
  if (networkOn){     // werken met console? => wachten tot wifi/lan en mqtt verbonden zijn.
    do{               //wacht tot wifi/lan en mqtt verbonden is
      delay(1);
    } while( networkState != Network_UP_MQTT_UP);
  }

  initLcdSetup();         // init Lcd display achteraan het spel 
  
  writeLcdSetup("game setup", "StartWaarden");
  setupStartWaarden();        // set start met de vraag om alle knoppen op 0 te zetten
}
 

//***************************************************************************
// loop
//***************************************************************************
void loop(){
  
  spellichtAanUit();            // zet spel led volgens state aan/uit
  if (state > 1 ){              // spelen = state > 1 en niet spelen = state = 0 of 1 => Uit of Straf
    if (!einde){                // resultaat nog niet gevonden
      state = Running;
      speelspel();
   }
  }
  else {
    if ( !networkOn){ // je mag spelen zonder console
      state = Initialising; 
      einde = false;
      writeLcdSetup(nettxt[networkOn] + " netwerk", "Spel staat aan",false);       // schrijf lcdSetup dat spel aanligt zonder wifi
    }
    else{                           // Je mag niet spelen => strafpunten ??
      if (state < 2){               // spel is uit of straf
        straftest();                // kijk of er nog gestraft is
      }
    }
  }
}

wifi and ethernet variables:

// de wifi en mqtt gegevens staan in config.txt
char wifiSSID[32];            // SSID of the network to join
char wifiPassword[32];        // Wi-Fi password if required
char remoteMQTTServer[16];    // IP address of remote MQTT server Brewhouse
char remoteMQTTUser[16];
char remoteMQTTPass[16];

// GLOBALS Ethernet
byte mac[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };  // 16/7: mac wordt opgehaald in ethernet.ino
#define ETHERNET_RESET_PIN      13      // ESP32 pin to reset pin from W5500 is niet meer in gebruik/ 16/7: verplaatst 15 naar 13
#define ETHERNET_CS_PIN         17      // ESP32 tx2 pin to CS pin from W5500 is connected

// GLOBALS Wifi/Lan en MQTT
WiFiClient wifiClient;
EthernetClient ethClient;

// MQTT client based on the chosen network
PubSubClient mqttClient;

// A re-usable buffer to hold MQTT messages to be sent/have been received
char mqttMsg[512];
// The MQTT topic in which to publish a message
char mqttTopic[32];

// Keep track of connection state of both WiFi and MQTT network
enum : byte { Network_DOWN_MQTT_DOWN, Network_STARTING_MQTT_DOWN, Network_UP_MQTT_DOWN, Network_UP_MQTT_STARTED, Network_UP_MQTT_UP } connectionState;
byte networkState = Network_DOWN_MQTT_DOWN;

// Track state of overall puzzle
enum State {Uit, Straf, SetToZero, Initialising, Running, Solved, Autosolve};
State state = Uit;                // spel staat uit

// Track Net of type network
String nettxt[3] = {"Geen", "Wifi", "Lan"};
enum : byte {Geen, Wifi, Lan} net;
byte networkOn = Geen;                // wifi/lan staat uit

network.ino

//***************************************************************************
// init lcdsetup aan de achterkant
//***************************************************************************
void initLcdSetup(){
  Serial.println("initLcdSetup running");
  lcdsetup.init();           // initialize the lcdsetup
  lcdsetup.backlight();
  lcdsetup.clear();
  lcdsetup.setCursor(0, 0);
  lcdsetup.print("Opstarten");
}

//************************************************/
// Schrijf op lcd Setup display
//************************************************/

void writeLcdSetup(String L1, String L2){   // writeLCDSetup zonder wacht definitie
  writeLcdSetup( L1,  L2, true);            // er wordt automatisch 1 sec gewacht
}

void writeLcdSetup(String L1, String L2, bool wacht){   // writeLCDSetup met wacht definitie

  lcdsetup.clear();
  lcdsetup.setCursor(0, 0);
  lcdsetup.print(L1);
  lcdsetup.setCursor(0, 1);
  lcdsetup.print(L2);
  Serial.println("write LCD: " +L1+" "+L2);
  if(wacht){
    delay(500);                                    // 16/7: aangepast van 1000 naar 500
  }
}

//***************************************************************************
// is er data van MQTT
//***************************************************************************
void readMqtt(const JsonDocument& jsonDoc) {
  // Act upon command received
//  Serial.print("received Mqtt command: ");Serial.println(jsonDoc["command"]);           // waarom werkt dit niet !!!
  if(jsonDoc["command"] == "SOLVE") {
    if (state != Uit){          // solved werkt enkel als de game aanligt
      if (state != Solved ){    // werkt niet als die al opgelost is
        state = Autosolve;
        autosolve();
      }
    }  
  }
  else if(jsonDoc["command"] == "RESET") {
    writeLcdSetup("Console reset", "ontvangen",false);    // schrijf schakel uit via console
    setupStartWaarden();   // reset alle gegevens van het spel
    writeLcdSetup(nettxt[networkOn] + " netwerk", "Spel staat UIT",false);    // schrijf schakel uit via console
    state = Uit;             // spel uitgeschakeld
    writeMqtt();
  }
  else if(jsonDoc["command"] == "AANUIT") {
    if (state == Uit){
      writeLcdSetup(nettxt[networkOn] + " netwerk", "Spel staat AAN",false);    // schrijf spel klaar via console
      state = Initialising;  // start een nieuw spel
    }
    else {
      writeLcdSetup(nettxt[networkOn] + " netwerk", "Spel staat UIT",false);    // schrijf schakel uit via console
      state = Uit;           // spel uitgeschakeld
      setupStartWaarden();   // vraag om alle schakelaars eerst op zero te zetten
    }
    writeMqtt();
  }
  
  else if(jsonDoc["command"] == "AAN") {
    if (state == Uit || state == Initialising){
      writeLcdSetup(nettxt[networkOn] + " netwerk", "Spel staat AAN",false);    // schrijf spel klaar via console
      state = Initialising;  // start een nieuw spel
//      setupStartWaarden();   // set nieuwe start waarden
    }
    writeMqtt();
  }

  else if(jsonDoc["command"] == "UIT") {
    state = Uit;           // spel uitgeschakeld
    setupStartWaarden();   // set nieuwe start waarden
    writeMqtt();
    writeLcdSetup(nettxt[networkOn] + " netwerk", "Spel staat UIT",false);    // schrijf spel klaar via console
  }
    

}

//***************************************************************************
// * Mqtt and Wifi/Lan handler
//***************************************************************************

void handler_wifi_mqtt(void* parameter){
//void handler_wifi_mqtt(){
  // Callback when MQTT message received in topic to which we are subscribed 
  mqttClient.setCallback([](char* topic, byte* payload, unsigned int length) {
    // Create a JSON document from the MQTT message received. Note best practice is NOT to have a reusable 
    // JSON document, but create a new one each time it is needed.  https://arduinojson.org/v6/assistant/
    StaticJsonDocument<128> jsonDoc;      
    deserializeJson(jsonDoc, payload, length);
    // Process the contents of the update received
    readMqtt(jsonDoc);
  });

//  if (!testEthernet()){  //  false = Wifi of true = Lan
  if (!0){  //  false = Wifi of true = Lan  
    networkOn = Wifi;
    WifiTimeStamp = millis();  // set time voor wifi connectie error
    writeLcdSetup("Console setup", "met Wifi",false);
    setWifiEvent();
  }
  else{
    writeLcdSetup("Console setup", "via Lan",false);
    networkOn = Lan;
  }

//***************************************************************************
// test loopen herstel wifi/lan en mqtt volgens de networkOn value
//***************************************************************************

  for (;;) {            // loop forever
    if (networkOn){     // mag er wifi en MQTT verbinding gemaakt worden
      networkLoop();
      vTaskDelay(100 / portTICK_PERIOD_MS);// is hetzelde als een delay van 100ms
    }
  }
}

//***************************************************************************
// * A robust method that re-establishes connection to Wi-Fi LAN network and MQTT server,
// * in the event of dropped connection/power loss etc.
// * See https://esp32.com/viewtopic.php?t=16109#p61846
//***************************************************************************
void networkLoop() {

  switch (networkState) {
    // If there is no Wi-Fi connection, in testEthernet there is a Lan connection if possible
    case Network_DOWN_MQTT_DOWN:
      digitalWrite(BildinLed, true);                // wifiled aan doen, geen verbinding
      if (networkOn == Wifi){
        WifiDown();
        networkState = Network_STARTING_MQTT_DOWN;
      }
      else {
        EthernetDown();
        networkState = Network_UP_MQTT_DOWN;      // lan connected
      }
      break;
    // If the Wifi router connection was started
    case Network_STARTING_MQTT_DOWN:
    // Allow 15 seconds since attempting to join the WiFi
      if (millis() - WifiTimeStamp >= 15000) {
        // Otherwise, if the WLAN router connection was not established
        Serial.println("Failed to start WiFi");
        writeLcdSetup("Staat " + String(wifiSSID), "router aan ?",false);    // schrijf geen router verbinding 
        delay(20000);
        WifiTimeStamp = millis();  // set time voor wifi connectie error
        // Clear the connection for the next attempt
        WiFi.disconnect();
        // And reset the state machine to its initial state (restart)
        networkState = Network_DOWN_MQTT_DOWN;
      }
      break;
    // If the Wifi/LAN router connection was established
    case Network_UP_MQTT_DOWN: 
      // And if no MQTT broker connection was established yet
      digitalWrite(BildinLed, true);                // led aan doen, geen verbinding

      if (networkOn == Wifi){
        setupMqtt(remoteMQTTServer,1883,wifiClient);     // voor wifi
      }
      else {
        setupMqtt(remoteMQTTServer,1883,ethClient);     // voor lan 
      }
      
      if (!mqttClient.connected()) {
        connectToMqtt();
      }
      networkState = Network_UP_MQTT_STARTED;
      break;
    // If the MQTT broker connection was started
    case Network_UP_MQTT_STARTED:
      if(mqttClient.connected()) {
        Serial.println("LAN and MQTT connected");
        mqttClient.publish("ToHost", "Hi there");        
        // Subscribe to topics specifically for this device
        snprintf(mqttTopic, 32, "ToDevice/%s", deviceID);
        mqttClient.subscribe(mqttTopic);
        // Subscribe to topics intended for ALL devices on network
        mqttClient.subscribe("ToDevice/All");
        // Advance the state machine
        networkState = Network_UP_MQTT_UP;
      }
      else {
        networkState = Network_UP_MQTT_DOWN;
      }
      break;
    // If both the LAN router and MQTT broker connections were established
    case Network_UP_MQTT_UP:
      digitalWrite(BildinLed, false);                // wifiled uit doen, er is een verbinding
      if (networkOn == Wifi){
        if(mqttClient.connected()) {
        mqttClient.loop();
        }
        else{
          networkState = Network_UP_MQTT_DOWN;
        }
      }
      else {       // voor lan
        if (Ethernet.linkStatus() == LinkOFF){
          Serial.println("ethernet not ok");
          delay(2000);
          ESP.restart();        // Ethernet not ok => restart esp
        }
        else {
          if(mqttClient.connected()) {
          mqttClient.loop();
          }
          else{
            networkState = Network_UP_MQTT_DOWN;
          }
        }
      }
      
    break;
  }
}

//*************************************************************** 
// * Read config file
// **************************************************************
bool readconfigFile() {
  char * path;
  String line;
  int i;
  
  Serial.println("Mounting config.txt");
  if (!LittleFS.begin()) {
    Serial.println("LittleFS mount failed");
    return false;
  }
  

// ****************** lees "/config.txt";
  path = "/config.txt";
  #ifdef DEBUG  
    Serial.printf("Reading file: %s\n", path);
  #endif
  File file = LittleFS.open(path, "r");
  if (!file) {
    
    #ifdef DEBUG  
        Serial.println(F("Failed to open file for reading"));
    #endif
    return false;
  }

  while(file.available()) {
    line = file.readStringUntil('\n');
//    Serial.println(line);
    DynamicJsonDocument Doc(400);
    DeserializationError error = deserializeJson(Doc, line);
  if (error){
      Serial.printf("Failed to read file : %s\n", path);
      return false;
  }
  
// als er compiler problemen zijn met Doc["naam"]  naar een String var => ga naar de website
// https://arduinojson.org/v6/error/ambiguous-overload-for-operator-equal/  
  
    strcpy(wifiSSID, Doc["ssid"]);
    strcpy(wifiPassword, Doc["pasw"]);                       
    strcpy(remoteMQTTServer, Doc["mqttip"]);   
    strcpy(remoteMQTTUser, Doc["mqttuser"]);
    strcpy(remoteMQTTPass, Doc["mqttpasw"]);

//    Serial.println(wifiSSID);
//    Serial.println(wifiPassword);                       
//    Serial.println(remoteMQTTServer);   
//    Serial.println(remoteMQTTUser);
//    Serial.println(remoteMQTTPass);
    
  file.close();
  }
  return true;
}  

//*************************************************************** 
// * scan all the i2c modules
// **************************************************************
void ScanI2C (){

// scan I2C address
  byte error, address;
  int nDevices;
  
  Serial.println("Scanning...");
  nDevices = 0;
  for(address = 1; address < 127; address++ ) 
  { Wire.beginTransmission(address);
    error = Wire.endTransmission();
    if (error == 0)
        { Serial.print("I2C device found at address 0x");
          if (address<16) Serial.print("0");
          Serial.print(address,HEX);
          Serial.println("  !");
          String I2Cadr = "0x" + String(address,HEX);
          // writeLcdSetup("I2C device ",I2Cadr);
          if((address)==32) {Serial.println("PCF found on " + I2Cadr);I2C0x20 = true;} 
          if((address)==33) {Serial.println("PCF found on " + I2Cadr);I2C0x21 = true;} 
          if((address)==38) {Serial.println("LcdGame found on " + I2Cadr);I2C0x26 = true;} 
          if((address)==39) {Serial.println("LcdSetup found on " + I2Cadr);I2C0x27 = true;} 
          if((address)==64) {Serial.println("Servo board found on " + I2Cadr);I2C0x40 = true;} 
          if((address)==101){Serial.println("TouchKeypad found on " + I2Cadr);I2C0x65 = true;}  
          nDevices++;
          delay(200);
        }
       // else if (error==4) 
       //     { Serial.print("Unknown error at address 0x");
       //     if (address<16) Serial.print("0");
       //     Serial.println(address,HEX);
       //     }    
  }
  if (nDevices == 0) {Serial.println("No I2C devices found\n");
                    //  writeLcdSetup("No I2C device"," ");
                     }
  else Serial.println("done\n");
}  // end of scan

ethernet.ino

//***************************************************************************
// W5500 reset function   // de reset wordt niet gebruikt
//***************************************************************************
void ethernetReset(const uint8_t resetPin) {
//    pinMode(resetPin, OUTPUT);
//    digitalWrite(resetPin, HIGH);
//    delay(250);
//    digitalWrite(resetPin, LOW);
//    delay(50);
//    digitalWrite(resetPin, HIGH);
//    delay(350);
}

//***************************************************************************
// W5500 test ethernet timeout is in de library set to 6000 en niet 60000
//***************************************************************************
bool testEthernet() {
    // w5500 ethernet verbinding maken
    esp_read_mac(mac, ESP_MAC_ETH);    // ethernet macadres ophalen
    Ethernet.init(ETHERNET_CS_PIN);
    ethernetReset(ETHERNET_RESET_PIN);
    delay(100);
    writeLcdSetup("Ethernet module", "testen",false);
    if(Ethernet.begin(mac)){
      return true;
    }
//    Ethernet.end();
    return false;
}

//***************************************************************************
// W5500 connect to ethernet
//***************************************************************************
void EthernetDown() {
    // w5500 ethernet verbinding maken
    esp_read_mac(mac, ESP_MAC_ETH);    // ethernet macadres ophalen
    Ethernet.init(ETHERNET_CS_PIN);
    ethernetReset(ETHERNET_RESET_PIN);
    delay(100);


    Ethernet.begin(mac, STATIC_IP);
    // check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware){
      writeLcdSetup("Ethernet module", "niet aangesloten",false);    // schrijf lcd setup 
      delay(10000);
      ESP.restart();        // w5500 niet aangesloten => restart esp
    }
    // check for Ethernet cable
    if (Ethernet.linkStatus() == LinkOFF){
      writeLcdSetup("Ethernet kabel", "niet aangesloten",false);    // schrijf lcd setup 
      delay(10000);
      ESP.restart();        // Ethernet kabel niet aangesloten => restart esp
    }
}

//***************************************************************************
// W5500 instellen mqtt gegevens voor lan
//***************************************************************************
void setupMqtt(const char* hostname, uint16_t port, Client& _connectionClient) {
    mqttClient.setClient(_connectionClient);
    mqttClient.setServer(hostname, port);
}

//***************************************************************************
// W5500 verbinden van mqtt gegevens voor lan
//***************************************************************************
void connectToMqtt() {
    Serial.print(F("Starting MQTT connection to "));
    Serial.print(remoteMQTTServer);
    Serial.print(" with port: ");
    Serial.println(1883);
    // Start the connection
//        mqttClient.setKeepAlive(5);  
    if (mqttClient.connect(deviceID, remoteMQTTUser, remoteMQTTPass)) {
      networkState = Network_UP_MQTT_STARTED;
    }
    else {
      Serial.print(F("MQTT Failed. RC="));
      Serial.print(mqttClient.state());
      // Otherwise if the MQTT broker connection could not be established
      Serial.println(" Retrying...");
      writeLcdSetup("Geen MQTT", "Console aan ?",false);    // schrijf lcd setup geen MQTT verbinding 
      delay(10000);
      ESP.restart();        // het lukt niet om mqtt te starten => restart esp
    }
}

wifi.ino

//***************************************************************************
// Set Wifi event function
//***************************************************************************
void setWifiEvent(){
// Examples of different ways to register wifi events
  WiFi.onEvent(WiFiEvent);
  WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
  WiFiEventId_t eventID = WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){
      Serial.print("WiFi lost connection. Reason: ");
      Serial.println(info.wifi_sta_disconnected.reason);
  }, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);

}

//***************************************************************************
// Wifi is down, start new connection function
//***************************************************************************
void WifiDown(){
unsigned long testtijd;

  WiFi.disconnect();
  delay(100);
  WiFi.mode(WIFI_STA); // Operate only in STA station mode (i.e. client), not also in AP access point mode (i.e. server)
  WiFi.persistent(false); // Don't write Wi-Fi credentials to flash
  // Start the connection
  Serial.print("Starting WiFi connection to ");
  Serial.println(wifiSSID);
  testtijd = (millis() - WifiTimeStamp)/1000; // hoe lang zoekt men al wifi
  writeLcdSetup("Zoekt Wifi", "reeds "+ String(testtijd)+ " sec",false);    // schrijf wifi connectie maken zonder wachten
  if (!WiFi.config(STATIC_IP, GATEWAY, SUBNET)){
    Serial.println("Setting static IP failed");
  }
  WiFi.begin(wifiSSID, wifiPassword);
}

//***************************************************************************
// Wifi event function
//***************************************************************************
void WiFiEvent(WiFiEvent_t event)
{
    Serial.printf("[WiFi-event] event: %d\n", event);

    switch (event) {
        case ARDUINO_EVENT_WIFI_READY: 
            Serial.println("WiFi interface ready");
            break;
        case ARDUINO_EVENT_WIFI_SCAN_DONE:
            Serial.println("Completed scan for access points");
            break;
        case ARDUINO_EVENT_WIFI_STA_START:
            Serial.println("WiFi client started");
            break;
        case ARDUINO_EVENT_WIFI_STA_STOP:
            Serial.println("WiFi clients stopped");
            break;
        case ARDUINO_EVENT_WIFI_STA_CONNECTED:
            Serial.println("Connected to access point");
            break;
        case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
            WiFi.disconnect();  
            Serial.println("Disconnected from WiFi");
            networkState = Network_DOWN_MQTT_DOWN;
            break;
        case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE:
            Serial.println("Authentication mode of access point has changed");
            break;
        case ARDUINO_EVENT_WIFI_STA_GOT_IP:
            Serial.print(F("Connected to "));
            
            Serial.print(wifiSSID);
            Serial.print(F(", IP:"));
            Serial.println(WiFi.localIP());
            networkState = Network_UP_MQTT_DOWN;
            break;
        case ARDUINO_EVENT_WIFI_STA_LOST_IP:
            Serial.println("Lost IP address and IP address is reset to 0");
            break;
        case ARDUINO_EVENT_WPS_ER_SUCCESS:
            Serial.println("WiFi Protected Setup (WPS): succeeded in enrollee mode");
            break;
        case ARDUINO_EVENT_WPS_ER_FAILED:
            Serial.println("WiFi Protected Setup (WPS): failed in enrollee mode");
            break;
        case ARDUINO_EVENT_WPS_ER_TIMEOUT:
            Serial.println("WiFi Protected Setup (WPS): timeout in enrollee mode");
            break;
        case ARDUINO_EVENT_WPS_ER_PIN:
            Serial.println("WiFi Protected Setup (WPS): pin code in enrollee mode");
            break;
        case ARDUINO_EVENT_WIFI_AP_START:
            Serial.println("WiFi access point started");
            break;
        case ARDUINO_EVENT_WIFI_AP_STOP:
            Serial.println("WiFi access point  stopped");
            break;
        case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
            Serial.println("Client connected");
            break;
        case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED:
            Serial.println("Client disconnected");
            break;
        case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:
            Serial.println("Assigned IP address to client");
            break;
        case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED:
            Serial.println("Received probe request");
            break;
        case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
            Serial.println("AP IPv6 is preferred");
            break;
        case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
            Serial.println("STA IPv6 is preferred");
            break;
        case ARDUINO_EVENT_ETH_GOT_IP6:
            Serial.println("Ethernet IPv6 is preferred");
            break;
        case ARDUINO_EVENT_ETH_START:
            Serial.println("Ethernet started");
            break;
        case ARDUINO_EVENT_ETH_STOP:
            Serial.println("Ethernet stopped");
            break;
        case ARDUINO_EVENT_ETH_CONNECTED:
            Serial.println("Ethernet connected");
            break;
        case ARDUINO_EVENT_ETH_DISCONNECTED:
            Serial.println("Ethernet disconnected");
            break;
        case ARDUINO_EVENT_ETH_GOT_IP:
            Serial.println("Obtained IP address");
            break;
        default: break;
    }}

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info)
{
    Serial.println("WiFi connected");
    Serial.print("IP address: ");
    Serial.println(IPAddress(info.got_ip.ip_info.ip.addr));
} 

Good luck.

I wonder how you power the setup.
A dual-core ESP32 is power-hungry when WiFi kicks in (~400mA).
The W5500 also draws quite a bit (160mA).
Current draws are from memory.
Brownouts are likely if the power supply can't keep up with that.
Leo..

My power supply is a 5V adapter 2.4A. So I think the power is ok.