WiFiManager阻止循环代码执行问题求助
问题分析与解决方案
核心问题
你使用AP_NONE选项时,虽然能开启AP,但没有在主循环中轮询处理配置门户的请求,同时对AP_NONE的工作逻辑存在误解:AP_NONE仅让函数立即返回、不阻塞主循环,但需要你手动在loop()中调用handlePortal()来维持配置门户的正常运行,否则门户无法响应任何连接请求,看起来就像“未生效”。
具体问题点
- 缺少
handlePortal()轮询:查看WiFiConnect库的实现,startConfigurationPortal(AP_NONE)仅完成AP和DNS/HTTP服务器的初始化,不会自动在后台处理请求。必须在loop()中定期调用wc.handlePortal(),否则配置门户无法响应任何连接请求。 - 重复初始化AP:在
loop()中,当WiFi断开时重复调用startConfigurationPortal(AP_NONE),会多次初始化AP和服务器,可能导致资源冲突或异常。
修正后的代码
#include "WiFiConnect.h" #include <WiFiClient.h> #ifdef ARDUINO_ARCH_ESP8266 #include <ESP8266HTTPClient.h> #else #include <HTTPClient.h> #endif WiFiConnect wc; // For internet connection WiFiClient client; HTTPClient http; const int pin18=18; void configModeCallback(WiFiConnect *mWiFiConnect) { Serial.println("Entering Access Point"); } void startWiFi(boolean showParams = false) { wc.setDebug(true); /* Set our callbacks */ wc.setAPCallback(configModeCallback); //wc.resetSettings(); //helper to remove the stored wifi connection, comment out after first upload and re upload /* AP_NONE = Continue executing code, but you need to call handlePortal() in loop AP_LOOP = Trap in a continuous loop - Device is useless AP_RESET = Restart the chip AP_WAIT = Trap in a continuous loop with captive portal until we have a working WiFi connection */ if (!wc.autoConnect()) { // try to connect to wifi /* We could also use button etc. to trigger the portal on demand within main loop */ wc.startConfigurationPortal(AP_NONE);//if not connected show the configuration portal } } void setup() { Serial.begin(115200); while (!Serial) { delay(100); } Serial.println("...."); Serial.println("...."); delay (5000); startWiFi(); pinMode(pin18, OUTPUT); } void loop() { // 必须添加这一行,处理配置门户的DNS和HTTP请求 wc.handlePortal(); digitalWrite(pin18, HIGH); delay(500); digitalWrite(pin18, LOW); delay(500); delay(100); Serial.println("Testing with connection to internet..."); http.begin(client, "http://ftp.mirrorservice.org/sites/archive.ubuntu.com/ubuntu/"); int httpCode = http.GET(); if (httpCode > 0) { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server if (httpCode == HTTP_CODE_OK) { Serial.println("HTTP_CODE_OK"); } } else { Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } http.end(); // Wifi Dies? Start Portal Again (仅在未开启AP时初始化) if (WiFi.status() != WL_CONNECTED && !wc.getIsAP()) { if (!wc.autoConnect()) wc.startConfigurationPortal(AP_NONE); } delay (20000); }
关键修改说明
- 添加
wc.handlePortal()到loop():这是维持配置门户运行的核心,必须在每次循环中调用,确保DNS和HTTP请求被处理。 - 增加
!wc.getIsAP()判断:避免在已经处于AP模式时重复调用startConfigurationPortal,防止资源重复初始化。 - 更新注释:明确
AP_NONE的使用前提,需要手动处理门户请求。
额外说明
AP_NONE的设计逻辑是让设备在开启AP的同时继续执行主业务代码,但门户的请求处理需要开发者主动介入。如果没有调用handlePortal(),AP虽然会启动,但无法响应任何配置请求,看起来就像“未生效”。
内容的提问来源于stack exchange,提问作者dinghy
相关产品推荐
相关产品推荐

