You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP 12e接入点模式下定时重启及WiFi重连故障解决问询

问题排查与解决方案

问题分析

  1. 循环逻辑错误:你使用的do-while循环会在autoConnect()超时后立刻重复调用该函数,导致设备反复进入AP模式,完全没有等待路由器恢复的时间窗口。autoConnect()本身会优先尝试连接已保存的WiFi,失败才启动AP,你的循环强制重复这个流程,彻底违背了“超时后重启等待WiFi”的需求。
  2. 缺少超时重启机制:仅设置了WiFiManager的AP超时时间,但没有在超时后触发设备重启的逻辑,无法实现“AP模式运行6分钟后重启”的目标。
  3. EEPROM操作时机不合理:无论WiFi是否连接成功,都会执行EEPROM写入操作,可能导致原有配置被错误覆盖。

解决方案

  1. 移除错误的do-while循环,直接调用autoConnect()并根据返回值判断连接结果。
  2. 将WiFiManager的AP超时设置为6分钟(360秒),超时后若WiFi未连接则触发设备重启。
  3. 调整EEPROM写入逻辑,仅在用户通过AP完成新配置时才写入参数,避免覆盖已有配置。
  4. 使用ESP.restart()实现设备重启,确保重启前清理资源。

修正后的代码

#include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include <EEPROM.h>

// 全局变量声明(需补充你的变量定义)
char authorizationKey[32] = "";
char apiKey[32] = "";
char userNameKey[32] = "";

void setup() {
    Serial.begin(57600);
    
    WiFiManager wifiManager;
    // 添加自定义参数
    WiFiManagerParameter customAPIKey("authorizationKey", "Authorization Code", authorizationKey, 32);
    WiFiManagerParameter customAPIKey2("apiKey", "Time Zone #", apiKey, 32);
    WiFiManagerParameter customAPIKey3("userNameKey", "User Name", userNameKey, 32);
    
    wifiManager.addParameter(&customAPIKey);
    wifiManager.addParameter(&customAPIKey2);
    wifiManager.addParameter(&customAPIKey3);
    
    // 设置AP模式超时为6分钟(360秒)
    wifiManager.setTimeout(360);
    
    // 尝试自动连接WiFi,失败则启动AP等待配置
    bool connectSuccess = wifiManager.autoConnect("LEVEL1");
    
    // 连接失败,等待超时后重启设备
    if (!connectSuccess || WiFi.status() != WL_CONNECTED) {
        Serial.println("AP超时,即将重启设备");
        delay(1000);
        ESP.restart();
    }
    
    // 连接成功,获取新配置参数
    strcpy(authorizationKey, customAPIKey.getValue());
    strcpy(apiKey, customAPIKey2.getValue());
    strcpy(userNameKey, customAPIKey3.getValue());
    
    // 仅当用户输入了新的apiKey时,才写入EEPROM
    String rrr = apiKey;
    if (rrr.length() > 0) {
        Serial.println("保存新配置到EEPROM");
        EEPROM.begin(512);
        
        String uuu = authorizationKey;
        String www = apiKey;
        String yyy = userNameKey;
        String fff = www + ",";
        String vvv = yyy + ",";
        
        // 写入Authorization Code
        for(int i=0; i<uuu.length(); i++) {
            EEPROM.write(0x06 + i, uuu[i]);
        }
        // 写入Time Zone
        for(int i=0; i<fff.length(); i++) {
            EEPROM.write(0x50 + i, fff[i]);
        }
        // 写入User Name
        for(int i=0; i<vvv.length(); i++) {
            EEPROM.write(0x90 + i, vvv[i]);
        }
        
        EEPROM.commit();
        EEPROM.end();
    }
    
    Serial.println("WiFi连接成功");
    delay(1000);
    
    // 后续添加MQTT连接等逻辑
}

void loop() {
    // 你的业务逻辑
}

内容的提问来源于stack exchange,提问作者user1114881

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 23:44:52