struct WiFiConnection {
const char* ssid;
const char* password;
};
const WiFiConnection wifiConnections[] = {
{ "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; // 当前尝试的连接索引
ESP8266WiFiMulti wifiMulti;
WiFiClient client;
void addWiFiConnections() {
int numConnections = sizeof(wifiConnections) / sizeof(wifiConnections[0]);
for (int i = 0; i < numConnections; i++) {
wifiMulti.addAP(wifiConnections[i].ssid, wifiConnections[i].password);
}
}
//链接网络
void manageWiFiConnection() {
if (WiFi.status() != WL_CONNECTED) {
lightFlash(120);
unsigned long currentTime = millis();
if (attemptConnection && currentTime - previousAttemptTime >= connectionAttemptInterval) {
Serial.println("WiFi connecting...");
if (wifiMulti.run() == WL_CONNECTED) {
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
} else {
attemptConnection = false;
previousAttemptTime = currentTime;
}
} else if (!attemptConnection && currentTime - previousAttemptTime >= retryInterval) {
Serial.println("30秒后再试");
// 等待30秒后重置标志和索引,重新开始尝试连接
attemptConnection = true;
currentConnectionIndex = 0;
}
}
}
解释
retryInterval记住是毫秒;
addWiFiConnections()函数是在void setup()中调用一次就可以,然后调用manageWiFiConnection();
manageWiFiConnection()函数最好也放置在loop()函数中,如果loop没有设置delay,建议设置一下