Arduino ESP8266 AP Web 代码
时间: 2023-08-16 07:08:46 浏览: 101
以下是一个基本的Arduino ESP8266 AP Web的代码示例,可以让你在ESP8266上建立一个简单的Web服务器,并进行基本的网络通信:
```C++
#include <ESP8266WiFi.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected successfully");
// Start the server
server.begin();
Serial.println("Server started");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
if (request.indexOf("/LED=ON") != -1) {
digitalWrite(LED_BUILTIN, HIGH);
} else if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(LED_BUILTIN, LOW);
}
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("");
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head><title>ESP8266 LED Control</title></head>");
client.println("<body>");
client.println("<h1>LED Control</h1>");
client.println("<p>Click to turn the LED <a href=\"/LED=ON\">ON</a> or <a href=\"/LED=OFF\">OFF</a>.</p>");
client.println("</body>");
client.println("</html>");
delay(1);
Serial.println("Client disconnected");
}
```
这个代码示例做的事情是:建立一个名为 "your_SSID" 的Wi-Fi网络,并设置密码为 "your_PASSWORD"。然后,它会建立一个Web服务器,当用户访问服务器的IP地址时,会看到一个简单的Web页面。此外,当用户点击页面上的链接时,会向服务器发送一个请求,然后服务器会响应并控制开关一个LED。
阅读全文