esp32用WiFi控制led开关
时间: 2024-01-07 15:45:28 浏览: 30
您可以使用以下步骤在ESP32上控制LED开关:
1. 首先,确保您已经将ESP32连上了WiFi。
2. 在Arduino IDE中,打开一个新的空白窗口,然后输入以下代码:
```
#include <WiFi.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Set LED GPIO
const int ledPin = 2;
WiFiServer server(80);
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to Wi-Fi network with SSID and password
Serial.begin(115200);
delay(10);
// We start by connecting to a 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");
// 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
int value = LOW;
if (request.indexOf("/LED=ON") != -1) {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf("/LED=OFF") != -1) {
digitalWrite(ledPin, LOW);
value = LOW;
}
// Set the LED accordingly
digitalWrite(ledPin, value);
// 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.print("LED is now: ");
if(value == HIGH) {
client.print("On");
} else {
client.print("Off");
}
client.println("<br><br>");
client.println("Click <a href=\"/LED=ON\">here</a> to turn the LED on<br>");
client.println("Click <a href=\"/LED=OFF\">here</a> to turn the LED off<br>");
client.println("</html>");
delay(1);
Serial.println("Client disonnected");
Serial.println("");
}
```
3. 将`your_SSID`和`your_PASSWORD`替换为您的WiFi网络凭据。
4. 将LED连接到ESP32上的GPIO 2引脚。
5. 将ESP32连接到计算机,并上传代码。
6. 打开串口监视器,您将看到ESP32连接到WiFi网络。
7. 打开Web浏览器,输入ESP32的IP地址,例如`192.168.1.100`。
8. 您将看到一个简单的Web页面,其中包含控制LED的按钮。
9. 单击“ON”按钮将打开LED,单击“OFF”按钮将关闭LED。
这样,您就可以使用ESP32和WiFi控制LED开关了。