通过网页点击使ESP8266亮灯
时间: 2023-11-15 18:05:33 浏览: 29
要通过网页点击使ESP8266亮灯,您需要编写一个基于HTTP的服务器,并在其中添加一个处理程序,该处理程序将处理来自浏览器的请求并将其转换为控制ESP8266的命令。
以下是一个简单的示例代码,可帮助您开始编写您自己的ESP8266服务器:
```
#include <ESP8266WiFi.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("New client connected");
String currentLine = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
if (c == '\n') {
if (currentLine.length() == 0) {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("");
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// Check if the button was pressed
if (digitalRead(D0) == LOW) {
client.println("<p>LED is on.</p>");
} else {
client.println("<p>LED is off.</p>");
}
client.println("<form method=\"get\">");
client.println("<input type=\"submit\" value=\"Toggle LED\">");
client.println("</form>");
client.println("</html>");
break;
} else {
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
// Check if the button was pressed
if (currentLine.endsWith("GET /?button=pressed")) {
digitalWrite(D0, !digitalRead(D0));
}
}
}
client.stop();
Serial.println("Client disconnected");
}
}
```
您需要将此代码上传到ESP8266,并将其连接到您的Wi-Fi网络。然后,您可以通过导航到ESP8266的IP地址(在串行监视器中显示)来访问它的Web服务器。
在Web页面上,您将看到一个按钮,用于切换LED的状态。单击该按钮将触发处理程序,并将发送一个请求,该请求将在当前行中包含“GET /?button=pressed”字符串。当处理程序检测到此请求时,它将切换LED的状态。
请注意,您需要将LED连接到ESP8266的某个引脚并在程序中指定该引脚。在上面的示例中,我们使用了D0引脚。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)