Robust Way to Retry Ethernet Connection During Setup

Hi,

I'm working on a battery powered project that contains a modem that I connect to from an Arduino MKR with Ethernet shield. When the system powers up, the modem needs some time to start, so the standard Ethernet examples sometimes fail either because the link is OFF (modem not powered on yet) or because it's not ready to assign a DHCP. I looked at some examples that use the main program loop to retry connecting, but I would like to use setup for this. I know I could put a big delay() into the setup function, but I think retrying would be better.
Here is my code:

  // Start Ethernet and UDP  
  while (Ethernet.begin(mac) == 0) {  
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present  
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {  
      Serial.println("Ethernet shield was not found.");  
    } else if (Ethernet.linkStatus() == LinkOFF) {  
      Serial.println("Ethernet cable is not connected.");  
    } 
    //Retry to connect to DHCP anyway
    Ethernet.maintain();
    delay(100); 
    }   
  }

Is this a good (robust) way to do this?

begin will retry the DHCP. you can remove maintain.

I would not retry for EthernetNoHardware

1 Like