esp8266调节灯亮度
时间: 2023-11-25 20:06:07 浏览: 143
以下是ESP8266控制板载LED灯亮度的代码实现:
```arduino
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Create an instance of the server
ESP8266WebServer server(80);
// LED pin
const int ledPin = 2;
// PWM frequency
const int freq = 5000;
// PWM channel
const int ledChannel = 0;
// PWM resolution
const int resolution = 8;
void setup() {
// Start Serial
Serial.begin(115200);
// Connect to Wi-Fi network
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);
server.on("/led", handleLed);
server.begin();
// Setup PWM
ledcSetup(ledChannel, freq, resolution);
ledcAttachPin(ledPin, ledChannel);
}
void loop() {
server.handleClient();
}
// Handle root url
void handleRoot() {
String html = "<html><head><title>ESP8266 LED Control</title></head><body>";
html += "<h1>ESP8266 LED Control</h1>";
html += "<p>GPIO 2 PWM value: ";
html += ledcRead(ledChannel);
html += "</p>";
html += "<form action=\"/led\" method=\"POST\">";
html += "<label for=\"pwm\">PWM value (0-255):</label>";
html += "<input type=\"range\" id=\"pwm\" name=\"pwm\" min=\"0\" max=\"255\" value=\"";
html += ledcRead(ledChannel);
html += "\">";
html += "<br><br>";
html += "<input type=\"submit\" value=\"Submit\">";
html += "</form>";
html += "</body></html>";
server.send(200, "text/html", html);
}
// Handle LED control
void handleLed() {
int pwm = server.arg("pwm").toInt();
ledcWrite(ledChannel, pwm);
server.sendHeader("Location", "/");
server.send(302, "text/plain", "LED updated");
}
```
该代码使用ESP8266WebServer库创建了一个Web服务器,可以通过浏览器访问该服务器并控制板载LED灯的亮度。在Web页面上,用户可以通过滑块调整PWM值,从而改变LED灯的亮度。代码中使用ledcWrite()函数来设置PWM值,使用ledcRead()函数来读取当前PWM值。
阅读全文