esp32通过网页配置WiFi代码
时间: 2023-12-31 13:04:38 浏览: 327
以下是ESP32通过网页配置WiFi的代码示例:
```C++
#include <WiFi.h>
#include <WebServer.h>
const char* ssid = "your_ssid"; // WiFi SSID
const char* password = "your_password"; // WiFi password
WebServer server(80); // Create a web server on port 80
void handleRoot() {
String html = "<html><body><h1>ESP32 WiFi Configuration</h1>";
html += "<form method=\"POST\" action=\"/connect\"><label>WiFi SSID:</label><input type=\"text\" name=\"ssid\"><br><label>WiFi Password:</label><input type=\"password\" name=\"password\"><br><input type=\"submit\" value=\"Submit\"></form>";
html += "</body></html>";
server.send(200, "text/html", html); // Send the HTML page to the client
}
void handleConnect() {
String ssid = server.arg("ssid"); // Get the SSID from the form
String password = server.arg("password"); // Get the password from the form
WiFi.begin(ssid.c_str(), password.c_str()); // Connect to the WiFi network
String html = "<html><body><h1>ESP32 WiFi Configuration</h1><p>Connecting to ";
html += ssid;
html += "...</p></body></html>";
server.send(200, "text/html", html); // Send the HTML page to the client
delay(5000); // Wait for the WiFi connection to be established
if(WiFi.isConnected()) {
html = "<html><body><h1>ESP32 WiFi Configuration</h1><p>Connected to ";
html += ssid;
html += ".</p></body></html>";
} else {
html = "<html><body><h1>ESP32 WiFi Configuration</h1><p>Unable to connect to ";
html += ssid;
html += ".</p></body></html>";
}
server.send(200, "text/html", html); // Send the HTML page to the client
}
void setup() {
Serial.begin(115200); // Start the serial communication
WiFi.mode(WIFI_STA); // Set the ESP32 in station mode
WiFi.disconnect(); // Disconnect from any previous connections
delay(1000); // Wait for the WiFi module to initialize
server.on("/", HTTP_GET, handleRoot); // Handle the root URL
server.on("/connect", HTTP_POST, handleConnect); // Handle the form submission
server.begin(); // Start the server
}
void loop() {
server.handleClient(); // Handle incoming client requests
}
```
此代码使用WebServer库创建一个Web服务器,当客户端访问根URL时,它将发送HTML表单以配置WiFi。当客户端提交表单时,服务器将连接到指定的WiFi网络,并向客户端发送连接状态的HTML页面。注意,此示例中未进行任何安全性检查,应在实际应用程序中进行修改以确保安全。
阅读全文