ESP8266热点配网-Arduino代码分享

介绍

之前发布过一篇有关ESP8266智能配网的分享,当时还是太年轻,可能误导了一些同学,其实完全没必要那么麻烦,所以这里今天分享一个热点的配网方式,首先是解决一个成功率,智能配网成功率极低,很多人反馈都是配网不成功,所以就改用新的ap热点配网。

原理说明

其实这个原理更容易理解,大致原理如下:

  1. ESP8266建立一个热点
  2. 再建立一个web服务,里面放一个配网的页面
  3. 搞定一些DNS相关的配置
  4. 当设备连接到ESP8266的热点时,就自动弹出配网页面
  5. 用户选择wifi信息,然后输入密码,即可实现配网
  6. ESP8266接受到密码以后就保存wifi信息后连接wifi

说明:这里主要是参考CSDN文章:ESP8266的Web配网以及强制门户的实现(连接wifi自动打开网页),具体大家可查阅原文,人家介绍的比较详细,文章写的也比较清楚,作为搬运工的我只是基于原文做了一些个人的优化配置在里面

演示图片

代码

代码有点长,请耐心看完就好了

#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>//配网页面代码
const char *page_html = "<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'><meta name='viewport'content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'><title>配置WIFI</title><style>*{margin:0;padding:0}body{font-size:16px;margin:0 15px;z-index:0}.flexcenter{display:flex;align-content:center;align-items:center}.button{width:40%;border-radius:5px;height:40px;background:none;border:1px solid green;font-size:20px;justify-content:space-evenly;color:green}.button:active{background:#ccc}.wifititle{display:flex;margin:0 15px;justify-content:space-between;font-size:22px;color:#333}.wifilist{display:flex;flex-direction:column;align-items:center;justify-content:space-between;font-size:25px;color:#ccc}divw{height:30px;border-bottom:1px solid#ccc;width:100%;background:none;margin-top:5px}divw:active{background:#50bfff}.title{justify-content:center;height:10%;font-size:35px;color:#725af3;letter-spacing:5px;text-shadow:0px 12px 10px#9d91bf}.content-input{height:20%;max-height:20%;display:flex;flex-direction:column}.input-text{display:flex;flex-direction:row;align-items:flex-end;justify-content:space-evenly;font-size:20px;color:#ccc}.input{width:76%;line-height:30px;font-size:25px;margin-top:15px;border-top:0;border-left:0;border-right:0;border-bottom:1px solid#ccc}.context-button{margin-top:15px;margin-bottom:15px;justify-content:space-around}.loading-svg-container{width:50px;height:50px}.path{stroke:#409eff;stroke-width:2;stroke-dasharray:95,126;stroke-dashoffset:0;animation:loading-dash 1.5s ease-in-out infinite}@keyframes loading-dash{0%{stroke-dasharray:1,126;stroke-dashoffset:0}50%{stroke-dasharray:95,126;stroke-dashoffset:-31px}to{stroke-dasharray:6,120;stroke-dashoffset:-120px}}.loading{width:40%;height:15%;position:absolute;background:#fff;display:flex;align-items:center;justify-content:space-around;top:30%;left:30%;flex-direction:column;color:#F4606C;border-radius:20px;overflow:hidden;font-size:14px;z-index:999}.box{width:100%;height:100%;position:fixed;background:#cccccc;opacity:0.8;margin-left:-15px;display:none}</style></head><body οnlοad='initData()'><div class='box'><div class='loading'><svg viewBox='0 0 50 50'class='loading-svg-container'><circle cx='25'cy='25'r='20'fill='none'class='path'></circle></svg><span id='tip'></span></div></div><div class='flexcenter title'>欢迎使用配置WIFI</div><div class='content-input'><div class='input-text'>SSID:<input class='input'id='ssid'type='text'value=''/></div><div class='input-text'>密码:<input class='input'id='pwd'type='password'value=''/></div></div><div class='flexcenter context-button'><button class='flexcenter button'οnclick='connwifi()'>提&nbsp;&nbsp;交</button><button class='flexcenter button'οnclick='reset()'>重&nbsp;&nbsp;置</button></div><div class='wifititle'><span>wifi列表</span><span style='color: blue'οnclick='getWifiList()'>刷新</span></div><div class='wifilist'id='wifilist'></div></body><script>function initData(){setTimeout(function(){getWifiList()},1000)}function showloading(msg){document.getElementsByClassName('box')[0].style.display='table';document.getElementById('tip').innerHTML=msg}function hideloading(){document.getElementsByClassName('box')[0].style.display='none';document.getElementById('tip').innerHTML=''}function getWifiList(){document.getElementById('tip').innerText='';showloading('搜索wifi中...');doget('/wifilist',function(result){if(result.indexOf('.nodata')!==-1){showloading('找不到有效wifi信息');setTimeout(function(){hideloading()},2000);return}hideloading();var arr=result.split(',');var html='';for(item of arr){if(item===''){continue}html+='<divw οnclick=\"setSsid(event)\">'+item+'</divw>'}document.getElementById('wifilist').innerHTML=html})}function setSsid(event){document.getElementById('tip').innerText='';document.getElementById('ssid').value=event.currentTarget.innerText}function reset(){document.getElementById('tip').innerText='';document.getElementById('ssid').value='';document.getElementById('pwd').value=''}function connwifi(){var ssid=document.getElementById('ssid').value;if(ssid===''||ssid===null||typeof(ssid)==='undefined'){showloading('SSID不能为空');setTimeout(function(){hideloading()},1000);return}var pwd=document.getElementById('pwd').value;var url='/configwifi?ssid='+ssid+'&pwd='+pwd;showloading('网络配置中...');doget(url,function(result){showloading(result);setTimeout(function(){hideloading()},1000)})}function doget(url,callback){var ajax=new XMLHttpRequest();ajax.open('get',url);ajax.send();ajax.onreadystatechange=function(){callback(ajax.response)}}</script></html>";const char *AP_NAME = "esp8266-config"; // wifi名字
IPAddress apIP(192, 168, 4, 1);        // esp8266-AP-IP地址
DNSServer dnsServer;                   //创建dnsServer实例
ESP8266WebServer server(80);           //创建WebServer/**@brief 访问主页回调函数*/
void handleRoot()
{server.send(200, "text/html", page_html);
}/**@brief Post回调函数*/
void handleConfigWifi()
{WiFi.setAutoConnect(true);                                         // 设置自动连接WiFi.begin(server.arg("ssid").c_str(), server.arg("pwd").c_str()); // 使用配网获取的wifi信息int count = 0;while (WiFi.status() != WL_CONNECTED){delay(500);count++;if (count > 50){ //如果5秒内没有连上,就开启Web配网 可适当调整这个时间server.send(200, "text/html", "wifi连接失败,请检查密码后重试。"); //返回保存成功页面break;                                                            //跳出 防止无限初始化}Serial.print(".");}if (WiFi.status() == WL_CONNECTED) //如果连接上 就输出IP信息 防止未连接上break后会误输出{Serial.print("WIFI Connected:");                               打印esp8266的IP地址Serial.println(WiFi.localIP());                                //打印esp8266的IP地址server.send(200, "text/html", "wifi连接成功,即将重启设备。"); //返回保存成功页面delay(3000);server.stop();}
}/**@brief 获取wifi列表回电函数*/
void handleWifiList()
{int n = WiFi.scanNetworks(); //开始同步扫描,将返回值存放在变量n中if (n > 0){char wifilist[640] = {0}; // 返回给网页的数据Serial.println("sacn wifi.");for (int i = 0; i < 20; ++i) //开始逐个打印扫描到的{sprintf(wifilist, "%s%s%s", wifilist, WiFi.SSID(i).c_str(), ","); // 组装信息返回给接口}Serial.print(wifilist);                  // 打印一下日志server.send(200, "text/html", wifilist); //返回保存成功页面return;                                  // 结束这里的操作}Serial.println("no any wifi.");           // 打印没有任何wifi日志server.send(200, "text/html", ".nodata"); //返回保存成功页面
}/**@brief 初始化WebServer*/
void initWebServer(void)
{WiFi.mode(WIFI_AP);                                         //初始化AP模式WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); //初始化AP模式WiFi.softAP(AP_NAME);                                   //初始化AP模式server.on("/", HTTP_GET, handleRoot);                 //设置主页回调函数server.onNotFound(handleRoot);                        //设置无法响应的http请求的回调函数server.on("/configwifi", HTTP_GET, handleConfigWifi); //设置Post请求回调函数server.on("/wifilist", HTTP_GET, handleWifiList);     // 设置获取wifi列表回调函数server.begin();                                       //启动WebServerSerial.println("WebServer started!");dnsServer.start(53, "*", apIP);
}void connectNewWifi(void)
{WiFi.mode(WIFI_STA);       //切换为STA模式WiFi.setAutoConnect(true); //设置自动连接WiFi.begin();              //连接上一次连接成功的wifiSerial.println("");Serial.print("Connect to wifi");int count = 0;while (WiFi.status() != WL_CONNECTED){delay(500);count++;if (count > 100){initWebServer(); //如果5秒内没有连上,就开启Web配网 可适当调整这个时间break;           //跳出 防止无限初始化}Serial.print(".");}Serial.println("");if (WiFi.status() == WL_CONNECTED) //如果连接上 就输出IP信息 防止未连接上break后会误输出{Serial.print("WIFI Connected!"); //打印esp8266的IP地址Serial.println(WiFi.localIP());  //打印esp8266的IP地址}
}void setup()
{Serial.begin(115200);           //初始化基础WiFi.hostname("Smart-ESP8266"); //设置ESP8266设备名connectNewWifi();
}void loop()
{server.handleClient();dnsServer.processNextRequest();
}

参考文章

ESP8266的Web配网以及强制门户的实现(连接wifi自动打开网页)

ESP8266热点配网-Arduino代码分享相关推荐

  1. ESP8266 web配网微信小程序配网 全平台配网库 arduino 傻瓜式通用库

    wifi_link_tool esp8266通用配网库 (arduino) 库地址:点击进入GitHub 这是一个为esp8266设计的通用配网库 该库免费提供 使用请注明出处 允许毕业设计使用本库 ...

  2. ESP8266开发、ESP8266连接阿里云物联网、天猫精灵控制esp8266、esp8266一键配网、智能家居

    ESP8266开发.ESP8266连接阿里云物联网.天猫精灵控制esp8266.esp8266一键配网.智能家居 项目介绍 最近会 将arduino IDE开发ESP8266中一些值得记录得部分写下来 ...

  3. 【ESP32_8266_WiFi (十三)】ESP8266自动配网 – WiFiManager库使用说明

    文章目录 ESP8266自动配网 – WiFiManager库使用说明 1 WiFiManager库使用说明 1.1 WiFi配置流程 1.2 WiFi配置示例程序 1.2.1 预备程序 – 清理ES ...

  4. 【AT指令使用】安信可ESP-12S/ESP32S模组AT固件应用之微信小程序热点配网OTA升级

    目录 前言 一.Web 服务配网 二.操作过程 1.烧录带有Web服务功能的AT固件 2.Web服务配网过程 2.1 ESP-12S/ESP32-S搭建Web服务器 2.2 微信小程序部分的操作 3. ...

  5. Arduino+ESP8266自动配网并上传温湿度、光照强度到OneNET

    前言:     从接触ESP8266到现在有一段时间了,也感受到ESP8266的强大,其高性价比给极客者们带来了极大的福音.之前用ESP8266改装了一部遥控车,使其能用手机控制,手机app是用易安卓 ...

  6. 用手机软件给ESP8266一键配网

    ESP8266在连接路由器时,可以直接在程序中输入路由器的SSID和密码,那么当位置变了以后怎么办?这篇博客我们就来谈谈如何用手机给ESP8266一件配网.在Arduino中新建一个文件,输入以下代码 ...

  7. 【AT篇】与硬件平台无关,微信小程序softAP热点配网安信可 Wi-Fi 模块入网示例。(附带Demo)

    文章目录 一 材料准备 二 实现目的 三 配置的数据交互协议 3.1 小程序发送网络信息阶段 3.2 模组连接路由器的回调: 四 配置原理和过程 五 设备端 AT 交互过程 一 材料准备 设备:已烧录 ...

  8. 基于ESP8266的四旋翼无人机代码分享,该无人机可以爬墙哦

    1.整机效果和电路图如下: 2.代码: 代码链接在:https://github.com/AnishDey27/Wall-Climbing-Drone/blob/main/Node%20MCU%20C ...

  9. python 百度云api_Python使用百度API上传文件到百度网盘代码分享

    # coding:UTF-8 import urllib import urllib2 __author__ = 'Administrator' from poster.encode import m ...

  10. ESP8266 Blinker 小爱同学 本地控制 手机配网 四路开关 物联网 arduino编程详细注释

    作为一名注册12年CSDN的电脑爱好者,没有从事喜欢的IT行业还是颇有那么一丝丝的想念. 通过一段时间的arduino编程和ESP8266学习,参考示例程序等,完善了自己的一份小爱同学四开关控制的程序 ...

最新文章

  1. 项目管理经验谈——来自项目管理群的讨论
  2. Meson:支持Netflix的机器学习工作流
  3. 深入浅出解释FFT(四)——fft分析信号频率和相位
  4. k8s组件说明:主要组件统一说明
  5. typescript的类型描述_一文学懂TypeScript的类型
  6. FireBug调试工具笔记
  7. python用matplotlib画图时将标签竖着显示
  8. php preserve keys,PHP常用的数组函数
  9. hpuoj--校赛--特殊的比赛日期(素数判断+模拟)
  10. redis 实战面试
  11. @Import注解的作用
  12. 表达式计算引擎-JEP
  13. 谈谈项目成本管理遇到的难题及解决措施
  14. 软件开发项目人员配置
  15. Open Aspect Target Sentiment Classification with Natural Language Prompts
  16. matlab来解决城市设计,Matlab的实际应用设计(经典).doc
  17. 七剑下天山?七步搞定DB2查询优化!
  18. HaLoop—适用于迭代计算的Hadoop
  19. [c++]实现分数计算器设计
  20. [ 英语 ] 马斯克抱水槽“入主”推特总部中那句 Let that sink in 到底是什么梗?

热门文章

  1. vue脚手架学习笔记
  2. /dev/null空字符设备文件
  3. map和foreach的区别和应用场景_面试官:说说UDP和TCP的区别及应用场景
  4. win10如何打开摄像头_win10系统,蓝牙关闭,如何打开?
  5. matlab中unique的作用,matlab中的unique函数详解
  6. java 用户行为记录_大型网站用户行为记录的一个实现
  7. nginx 没有cookie_nginx实现负载均衡的原理及策略
  8. php 判断输入字符串,php 判断(输入框) 字符串函数
  9. hash redis springboot_在SpingBoot中使用Redis对接口进行限流
  10. linux shell读取文件,shell脚本中读取文件的方法