esp8266点灯代码
时间: 2023-10-17 22:06:40 浏览: 70
以下为 ESP8266 点灯代码,您可以参考:
```
#include <ESP8266WiFi.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const int ledPin = 4;
WiFiServer server(80);
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
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");
server.begin();
Serial.println("Server started");
}
void loop() {
WiFiClient client = server.available();
if (!client) {
return;
}
Serial.println("new client");
while(!client.available()){
delay(1);
}
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
if (request.indexOf("/LED=ON") != -1) {
digitalWrite(ledPin, HIGH);
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
}
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>ESP8266 WiFi LED Control</h1>");
client.println("<p>Click <a href=\"/LED=ON\">here</a> to turn the LED on</p>");
client.println("<p>Click <a href=\"/LED=OFF\">here</a> to turn the LED off</p>");
client.println("</body>");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
```
此代码实现了一个简单的 web 服务器,并允许远程控制 ESP8266 上的 LED。您可以通过访问 http://esp8266_ip_address/LED=ON 和 http://esp8266_ip_address/LED=OFF 打开/关闭 LED。当用户访问 ESP8266 时,ESP8266 将返回一个包含两个链接的网页,一个为开灯,一个为关灯。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)