WiFiNINA library question: Using DELAY?

Hi all, arduino noobe here. Using MKR 1010 and WiFiNINA library to establish Wifi connectivity.

A number of sample sketches, including Arduino IDE --> File --> Examples --> WiFiNINA --> ConnectWithWPA include a section of Arduino code as follows:

// attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

My question concerns the statement "delay(10000)."

Why is it necessary to include a delay loop, when the code already includes a WHILE loop that persists until connected (assuming I'm interpreting the code correctly)? Meaning, if the code has verified connection is established, why is it necessary to wait 10 seconds more? Is this an artifact of the library, the hardware, or something else - and is there a more elegant way to write the code instead of the frowned-upon delay method seen here? I'd appreciate your insight. Thank you.

I'll guess that it's an attempt to be a good neighbor to other devices on the same WiFi. If it sees a failure, spamming continuously with constant retries isn't helpful.

Why it delays even if a connection was established is less easy to explain though.

Here is the wifi setup function from one of my projects:

void setup_wifi() {
  uint8_t wait = 0;
  while (WiFi.status() != WL_CONNECTED) {
    if (wait) {
      --wait;
    }
    else {
      wait = 40;
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, pass);
    }
    delay(500);
    Serial.println("Waiting... ");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

Use or modify as you like.

I didn't think of that, wildbill, when reading the code. The loop waits if the current connection attempt fails, then tries again. Silly me. I appreciate the clarification.

Thank you, Perry. This is very helpful.

1 Like

thanks for sharing perry really helpful>

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