Checking WiFi status methods

I had some code that ran on an ESP-32 correctly a few months ago. Now it fails to connect to WiFi. I have changed the code to work, but not sure why one works and not the other. I've included the the WiFi setup code.

The code that does work is below:

void setup_wifi() {
  
  // We start by connecting to a WiFi network
  Serial.println();
  
  WiFi.begin(ssid, password);
  
  Serial.print("Connecting to ");
  Serial.println(ssid);
  delay(100);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

The code that does not work is below:

int status = WL_CONNECTED;

void setup_wifi() {
  
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  delay(100);
  status = WiFi.begin(ssid, password);
  while (status != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
    status = WiFi.begin(ssid, password);
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

The code that does not work just prints out '.....' and never connects.

In the second example you tell the WiFi stack to begin again and again. While in the first example you call begin once and then patiently wait for the WiFi stack to connect, asking it only for an update of the status.

Thanks, I kept looking at the code and not seeing the obvious. I guess I meant the second example to be:

status = WiFi.begin(ssid, password);
  while (status != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
    status = WiFi.status();
  }

You're welcome. Sometimes you need a second pair of eyes. :slight_smile:

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