arduino esp32 开发 wifi实现AP STA 模式网页更改wifi 配置 AP配置 保存到LittFs 代码实现
时间: 2023-10-04 11:13:47 浏览: 220
好的,以下是一个简单的示例代码,演示如何使用 Arduino ESP32 开发板实现 Wi-Fi 的 AP STA 模式、网页更改 Wi-Fi 配置和 AP 配置、以及将配置保存到 LittleFS 文件系统中。请注意,这只是一个示例代码,你需要根据你的具体需求进行修改和调整。
```
#include <WiFi.h>
#include <WebServer.h>
#include <LittleFS.h>
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
const char* ap_ssid = "MY_ESP32_AP";
const char* ap_password = "MY_ESP32_PASSWORD";
WebServer server(80);
void handleRoot() {
// Display the Wi-Fi configuration form
String html = "<html><body><h1>Wi-Fi Configuration</h1>";
html += "<form method=\"POST\" action=\"/save\">";
html += "SSID: <input type=\"text\" name=\"ssid\"><br/>";
html += "Password: <input type=\"password\" name=\"password\"><br/>";
html += "AP SSID: <input type=\"text\" name=\"ap_ssid\"><br/>";
html += "AP Password: <input type=\"password\" name=\"ap_password\"><br/>";
html += "<input type=\"submit\" value=\"Save\">";
html += "</form></body></html>";
server.send(200, "text/html", html);
}
void handleSave() {
// Save the Wi-Fi configuration to LittleFS
String ssid = server.arg("ssid");
String password = server.arg("password");
String ap_ssid = server.arg("ap_ssid");
String ap_password = server.arg("ap_password");
String json = "{\"ssid\":\"" + ssid + "\",\"password\":\"" + password + "\",\"ap_ssid\":\"" + ap_ssid + "\",\"ap_password\":\"" + ap_password + "\"}";
File configFile = LittleFS.open("/config.json", "w");
if (configFile) {
configFile.print(json);
configFile.close();
}
server.send(200, "text/plain", "Configuration saved.");
}
void setup() {
// Initialize LittleFS
if (!LittleFS.begin()) {
Serial.println("Failed to initialize LittleFS.");
while (1) {}
}
// Load Wi-Fi configuration from LittleFS
File configFile = LittleFS.open("/config.json", "r");
if (configFile) {
size_t size = configFile.size();
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
configFile.close();
Serial.println("Loaded configuration:");
Serial.println(buf.get());
// Parse JSON data and apply Wi-Fi and AP configuration
String ssid, password, ap_ssid, ap_password;
// ...
// You need to write code to parse JSON data and apply Wi-Fi and AP configuration here
// ...
}
else {
Serial.println("Failed to open configuration file.");
}
// Start Wi-Fi in AP STA mode
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
WiFi.softAP(ap_ssid, ap_password);
// Start the web server
server.on("/", handleRoot);
server.on("/save", handleSave);
server.begin();
}
void loop() {
server.handleClient();
}
```
这段代码使用 ESP32 的 LittleFS 文件系统来保存 Wi-Fi 配置和 AP 配置。在 ESP32 启动时,它会从 LittleFS 文件系统中读取配置数据并应用它们。当用户访问网页并更改配置时,它会将配置保存到 LittleFS 文件系统中。
阅读全文