网页里有个滑条,滑动滑条能给esp8266发送灯的亮度的代码
时间: 2024-03-17 21:47:50 浏览: 56
arduino+esp8266LED灯代码
好的,以下是一个简单的示例代码,使用Web服务器和ESP8266控制LED的亮度。你可以将其上传到ESP8266中:
```c
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
// Replace with your network credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// Set LED GPIO
const int ledPin = 5;
// Create an instance of the server
ESP8266WebServer server(80);
// Track LED Brightness
int brightness = 0;
// Handle root URI
void handleRoot() {
server.send(200, "text/html", "<html><body><h1>ESP8266 LED Control</h1><form action='/brightness' method='POST'><input type='range' name='brightness' min='0' max='255' onchange='this.form.submit()'><br>Brightness: <span id='currentBrightness'>0</span></form><script>document.querySelector('#currentBrightness').textContent=document.querySelector('input[type=\"range\"]').value;</script></body></html>");
}
// Handle brightness URI
void handleBrightness() {
brightness = server.arg("brightness").toInt();
analogWrite(ledPin, brightness);
server.send(200, "text/html", "Brightness set to: " + String(brightness));
}
void setup() {
// Set LED pin mode
pinMode(ledPin, OUTPUT);
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
// Print connection details
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Attach handlers to server
server.on("/", handleRoot);
server.on("/brightness", handleBrightness);
// Start server
server.begin();
Serial.println("Server started");
}
void loop() {
// Handle client requests
server.handleClient();
}
```
这段代码使用ESP8266WebServer库创建了一个Web服务器,监听80端口。当访问根URL时,会显示一个HTML页面,其中包含一个滑块,用于控制LED的亮度。滑块的值将以POST请求发送到/brightness URI。当收到/brightness POST请求时,会将LED的亮度设置为滑块的值。
阅读全文