至強ESP8266Web配網,利用FS閃存檔案系統+EEPROM記錄配網資訊和相關引數設定
FS閃存檔案系統和EEPROM的使用時二選一的,可以任意一種作為你的備選存盤相關引數的方案來實施,
每個人的個性化需求不一樣,可以根據個人的需求做相關的移植即可,已經相當精簡,內容只涉及配網和存盤案例引數設定的,移植也非常方便,
EEPROM讀寫函式都是現成寫好的,直接拿來使用即可,比起自己來寫的話,不一定能寫出這么優秀無bug的代碼,站在巨人的肩膀上實作自己的小目標要比一個人摸索要快捷省力,而且高效,容易得多,
注意事項:利用閃存檔案系統配置,上傳完程式后,再點擊工具-esp8266 Sketch Date Upload上傳配置后,才可以打開相關的Web配置頁面,進行配置,
本代碼已經成功驗證,并且反復斷電,驗證讀取FS和EEPROM是否正確,
配網頁面大同小異,如下圖:


配置完成后,串口列印資訊:

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <FS.h> //閃存檔案系統
#include <ArduinoJson.h>//json資料處理庫(第三方)
#include <EEPROM.h>
#define button D8 //設定手動清除FS閃存內容按鍵,loop里面已注釋,未開啟,
String ssid,password,location0,apikey0;
ESP8266WebServer server(80); //創建Web服務埠為80
void setup() {
pinMode(LED_BUILTIN, OUTPUT);//板載led
pinMode(button,INPUT);
digitalWrite(button,HIGH);
Serial.begin(115200);
EEPROM.begin(1024);
Serial.println("以下為EEPROM讀取的資訊:");
String count=Read_String(EEPROM.read(800),816);
delay(50);
Serial.println(count);
String pass=Read_String(EEPROM.read(804),856);
delay(50);
Serial.println(pass);
String loca= Read_String(EEPROM.read(808),884);
delay(50);
Serial.println(loca);
String api=Read_String(EEPROM.read(812),932);
delay(50);
Serial.println(api);
//Serial.println("");
if (SPIFFS.begin()) { // 打開閃存檔案系統,記得在你連接板子下載的程序中選Flash Size的時候不要選no SPIFFS,你可以選1M、2M、3M都無所謂,因為兩個檔案都很小
Serial.println("閃存檔案系統打開成功");
} else {
Serial.println("閃存檔案系統打開失敗");
}
if (SPIFFS.exists("/config.json")) { // 判斷有沒有config.json這個檔案
Serial.println("存在配置資訊,正在自動連接");
const size_t capacity = JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(2) + 156; //分配一個記憶體空間
DynamicJsonDocument doc(capacity);// 宣告json處理物件
File configJson = SPIFFS.open("/config.json", "r");
deserializeJson(doc, configJson); // json資料序列化
const char* ssid = doc["ssid"];
Serial.println(ssid);
const char* password = doc["password"];
Serial.println(password);
const char* location = doc["location0"];
Serial.println(location);
const char* apikey = doc["apikey0"];
Serial.println(apikey);
WiFi.mode(WIFI_STA); // 更換wifi模式
//WiFi.mode(WIFI_AP_STA);//設定模式為AP+STA
digitalWrite(LED_BUILTIN, HIGH);
WiFi.begin(ssid, password); // 連接wifi
Serial.println("AP設定完成");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
configJson.close();
Serial.println(WiFi.localIP());
} else {
Serial.println("不存在配置資訊,正在打開web配網模式");
IPAddress softLocal(192, 168, 1, 1);
IPAddress softGateway(192, 168, 1, 1);
IPAddress softSubnet(255, 255, 255, 0);
WiFi.softAPConfig(softLocal, softGateway, softSubnet);
WiFi.softAP("esp8266", "12345678"); //這里是配網模式下熱點的名字和密碼
Serial.println(WiFi.softAPIP());
}
server.on("/", handleRoot);//web首頁監聽
server.on("/set", handleConnect); // 配置ssid密碼監聽,感覺跟express的路由好像
server.begin();
}
void loop() {
server.handleClient();
// if (digitalRead(button) == 0) { //按鍵掃描,開啟后,會監測按鍵是否按下,按下后,將會清楚FS閃存,下次重啟將進入配網,
// removeConfig();
// }
}
void handleRoot() { //展示網頁的關鍵代碼
if (SPIFFS.exists("/index.html")) {
File index = SPIFFS.open("/index.html", "r");
server.streamFile(index, "text/html");
index.close();
}
}
void handleConnect() { //處理配置資訊的函式
ssid = server.arg("ssid"); //arg是獲取請求引數
password = server.arg("password");
location0 = server.arg("location"); //從JavaScript發送的資料中找laction的值
apikey0 = server.arg("apikey"); //從JavaScript發送的資料中找apikey的值
EEPROM.begin(1024);
Serial.println(ssid);
Write_String(800,816,ssid);
delay(30);
Serial.println(password);
Write_String(804,856,password);
delay(30);
Serial.println(location0);
Write_String(808,884,location0);
delay(30);
Serial.println(apikey0);
Write_String(812,932,apikey0);
delay(30);
server.send(300, "text/plain", "OK");
WiFi.mode(WIFI_STA); //改變wifi模式
WiFi.begin(ssid.c_str(), password.c_str());//String型別直接用會報錯,不要問為什么,轉成char *就行了,
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(WiFi.localIP());
removeConfig(); // 不管有沒有配置先洗掉一次再說,
String payload; // 拼接構造一段字串形式的json資料長{"ssid":"xxxxx","password":"xxxxxxxxxxx"}
payload += "{\"ssid\":\"";
payload += ssid;
payload += "\",\"password\":\"";
payload += password;
payload += "\",\"location0\":\"";
payload += location0;
payload += "\",\"apikey0\":\"";
payload += apikey0;
payload += "\"}";
File wifiConfig = SPIFFS.open("/config.json", "w");
wifiConfig.println(payload);//將資料寫入config.json檔案中
wifiConfig.close();
}
void removeConfig() {
if (SPIFFS.exists("/config.json")) { // 判斷有沒有config.json這個檔案
if (SPIFFS.remove("/config.json")) {
Serial.println("洗掉舊配置");
} else {
Serial.println("洗掉舊配置失敗");
}
}
}
//a寫入字串長度,b是起始位,str為要保存的字串
void Write_String(int a,int b,String str){
EEPROM.write(a, str.length());//EEPROM第a位,寫入str字串的長度
//把str所有資料逐個保存在EEPROM
for (int i = 0; i < str.length(); i++){
EEPROM.write(b + i, str[i]);
}
EEPROM.commit();
}
//a位是字串長度,b是起始位
String Read_String(int a, int b){
String data = "";
//從EEPROM中逐個取出每一位的值,并鏈接
for (int i = 0; i < a; i++){
data += char(EEPROM.read(b + i));
}
return data;
}
配網.html代碼:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WIFI配網</title>
</head>
<body>
<div class="main">
<h2>WIFI配網</h2>
<br>
<input class="input ssid" type="text" placeholder="SSID" name="ssid">
<input class="input password" type="password" placeholder="密碼" name="password">
<button class="button" onclick="sendData()">配置</button>
</div>
</body>
<script>
function sendData(){
let ssid = document.querySelector(".ssid").value
let password = document.querySelector(".password").value
if(ssid == "" || password == ""){
return
}
console.log(ssid,password)
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("配置成功")
alert("配置成功");
}
};
xhttp.open("GET", "set?ssid="+ssid+"&password="+password, true);
xhttp.send();
}
</script>
<style>
html,body{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.main{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
text-align: center;
}
.button{
outline: none;
box-sizing: border-box;
background: #f5f5f5;
border: 1px solid#bdbdbd;
border-radius: 18px;
color: #434343;
cursor: pointer;
display: block;
font-family: inherit;
font-size: 16px;
font-variant: normal;
font-weight: 400;
height: 2.14285714em;
line-height: 1.42857143;
margin: 18px auto;
padding: 4px 30px;
text-decoration: none;
white-space: nowrap;
}
.input{
resize: none;
outline: none;
margin: 4px auto;
height: 45px;
width: 80%;
border: 1px solid #d0d1ce;
padding-left: 15px;
font-size: 14px;
color: #000;
margin-left: 10px;
border-radius: 10px;
border: 1px solid #dcdfe6;
background-color: #fff;
}
</style>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/259807.html
標籤:其他
