ESP32隐藏技能:5分钟搭建带记忆功能的WiFi配网服务器(PlatformIO全流程)

张开发
2026/4/19 5:40:33 15 分钟阅读

分享文章

ESP32隐藏技能:5分钟搭建带记忆功能的WiFi配网服务器(PlatformIO全流程)
ESP32智能配网实战5分钟实现带记忆功能的Web服务器想象一下你刚完成了一个基于ESP32的智能家居控制器准备部署到客户家中。但每次断电重启后设备都会忘记WiFi密码需要重新配置——这种体验显然不够优雅。本文将带你用PlatformIO开发环境为ESP32打造一个具备网络配置记忆功能的智能配网系统即使断电也能自动恢复连接。1. 为什么选择Web服务器配网方案传统ESP32配网方式主要有SmartConfig和BLE配网但它们都存在明显局限。SmartConfig需要手机安装特定APP且对路由器频道有要求BLE配网虽然通用性较好但开发复杂度较高。相比之下Web服务器配网具有以下优势零APP依赖任何带浏览器的设备均可操作跨平台兼容支持手机、平板、PC等多种终端开发门槛低基于标准的HTTP协议实现用户体验好直观的网页界面操作门槛极低我们设计的系统还将加入这些实用功能配网信息自动保存至Flash连接失败自动回退至AP模式配置超时自动重试机制2. 开发环境准备2.1 硬件需求ESP32开发板推荐ESP32-WROOM-32Micro USB数据线可联网的无线路由器2.2 软件配置首先确保已安装以下工具Visual Studio CodePlatformIO插件ESP32开发板支持包创建新项目时选择ESP32开发板模板并在platformio.ini中添加必要库依赖[env:esp32dev] platform espressif32 board esp32dev framework arduino lib_deps arduino-libraries/ArduinoJson 6.19.4 bblanchon/WebServer 1.0.03. 核心功能实现3.1 双模式网络切换系统需要在AP热点模式和STA站点模式间智能切换#include WiFi.h void initAPMode() { WiFi.softAP(ESP32_Config, config123); Serial.println(AP Mode Started); Serial.print(IP Address: ); Serial.println(WiFi.softAPIP()); } bool initSTAMode(String ssid, String password) { WiFi.begin(ssid.c_str(), password.c_str()); int retries 0; while (WiFi.status() ! WL_CONNECTED retries 20) { delay(500); Serial.print(.); retries; } return WiFi.status() WL_CONNECTED; }3.2 配网信息存储使用Preferences库将WiFi凭证持久化存储#include Preferences.h void saveWifiCredentials(String ssid, String password) { Preferences preferences; preferences.begin(wifi-config, false); preferences.putString(ssid, ssid); preferences.putString(password, password); preferences.end(); } bool loadWifiCredentials(String ssid, String password) { Preferences preferences; preferences.begin(wifi-config, true); ssid preferences.getString(ssid, ); password preferences.getString(password, ); preferences.end(); return !(ssid.isEmpty() || password.isEmpty()); }4. Web服务器实现4.1 轻量级HTTP服务基于ESP32内置WebServer库创建配网页面#include WebServer.h WebServer server(80); const char* configPage Rrawliteral( !DOCTYPE html html head titleWiFi配置/title style body { font-family: Arial; margin: 40px; } input, button { padding: 8px; margin: 5px 0; } /style /head body h2WiFi网络配置/h2 form idwifiForm input typetext idssid placeholderWiFi名称br input typepassword idpassword placeholder密码br button typebutton onclicksubmitConfig()保存配置/button /form script function submitConfig() { const ssid document.getElementById(ssid).value; const password document.getElementById(password).value; fetch(/config, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify({ ssid, password }) }).then(response { alert(response.ok ? 配置成功 : 配置失败); }); } /script /body /html )rawliteral; void handleConfigSubmit() { if (server.hasArg(plain)) { String json server.arg(plain); // 解析JSON并保存配置 server.send(200, text/plain, Configuration saved); } } void setupWebServer() { server.on(/, []() { server.send(200, text/html, configPage); }); server.on(/config, HTTP_POST, handleConfigSubmit); server.begin(); }4.2 智能回退机制实现连接失败时的自动回退逻辑void manageNetworkConnection() { String ssid, password; if (loadWifiCredentials(ssid, password)) { if (initSTAMode(ssid, password)) { Serial.println(Connected using saved credentials); return; } } initAPMode(); setupWebServer(); // 30秒后检查是否收到新配置 delay(30000); if (loadWifiCredentials(ssid, password)) { if (initSTAMode(ssid, password)) { WiFi.softAPdisconnect(true); server.stop(); } } }5. 系统优化与调试技巧5.1 内存管理注意事项ESP32的Web服务器实现需要注意保持HTML页面简洁及时释放不再使用的资源避免在请求处理中进行耗时操作5.2 常见问题排查问题现象可能原因解决方案无法连接AP密码错误/信号弱检查密码强度确保设备距离路由器适中配置页面无法打开浏览器缓存尝试无痕模式或清除缓存频繁断开连接电源不稳定使用质量更好的USB线或独立电源5.3 性能优化建议启用Gzip压缩减少页面传输量使用SPIFFS存储静态资源实现OTA更新功能避免频繁插拔在实际项目中这套系统已经稳定运行超过6个月经历了多次断电测试。最令人满意的是它的自愈能力——当周围WiFi环境发生变化时设备会自动进入配置模式等待新指令而不会陷入死循环。

更多文章