可以实现指定时间内不断尝试连接wifi,当所有wifi都连接失败,那么就等待一段时间后再次出发(需要在loop中); 不需要delay计时间,不会阻塞程序运行.
struct WiFiConnection {
const char* ssid;
const char* password;
};
const WiFiConnection wifiConnections[] = {
{ "wifi名", "wifi密码" },
{ "wifi名", "wifi密码" }
};
unsigned long previousAttemptTime = 0; // 上次尝试连接的时间戳
const unsigned long connectionAttemptInterval = 10000; // 尝试连接之间的时间间隔: 10秒
const unsigned long retryInterval = 30000; // 连接失败后再次尝试之前的等待时间: 30秒
bool attemptConnection = true; // 是否尝试连接
int numConnections = sizeof(wifiConnections) / sizeof(wifiConnections[0]); // 可尝试的连接数
int currentConnectionIndex = 0; // 当前尝试的连接索引
//链接网络
void manageWiFiConnection() {
if (WiFi.status() != WL_CONNECTED) {
unsigned long currentTime = millis();
if (attemptConnection && currentTime - previousAttemptTime >= connectionAttemptInterval) {
if (currentConnectionIndex < numConnections) {
// 尝试下一个WiFi连接
Serial.print("Attempting to connect to: ");
Serial.println(wifiConnections[currentConnectionIndex].ssid);
WiFi.begin(wifiConnections[currentConnectionIndex].ssid, wifiConnections[currentConnectionIndex].password);
previousAttemptTime = currentTime;
currentConnectionIndex++;
} else {
// 尝试了所有WiFi连接但未成功,设置标志等待30秒后重新尝试
attemptConnection = false;
previousAttemptTime = currentTime;
}
} else if (!attemptConnection && currentTime - previousAttemptTime >= retryInterval) {
// 等待30秒后重置标志和索引,重新开始尝试连接
attemptConnection = true;
currentConnectionIndex = 0;
}
}
}