ESP32 Learn

Connect to Multiple WiFi Networks Safely

2025-09-18 路 ~1 min read
Table of contents
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <WiFi.h>

bool connectWiFi(const char * ssid,
  const char * pw, unsigned long timeout = 10000) {
  WiFi.begin(ssid, pw);
  unsigned long t = millis();
  while (WiFi.status() != WL_CONNECTED && millis() - t < timeout) {
    delay(300);
  }
  return WiFi.status() == WL_CONNECTED;
}
void setup() {
  Serial.begin(115200);
  const char * nets[][2] = {
    {
      "A",
      "a_pw"
    },
    {
      "B",
      "b_pw"
    },
    {
      "C",
      "c_pw"
    }
  };
  for (auto & n: nets) {
    if (connectWiFi(n[0], n[1])) {
      Serial.println("Connected!");
      break;
    }
  }
}
void loop() {}

馃敄 #wifi #networking