用html写个代码用来控制esp8266无极调光
时间: 2024-01-25 19:03:30 浏览: 163
网页控制esp8266的8个GPIO引脚状态翻转
5星 · 资源好评率100%
下面是一个基于 HTML、JavaScript 和 ESP8266 的无极调光控制代码示例:
HTML 代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>ESP8266 LED Dimmer</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>ESP8266 LED Dimmer</h1>
<input type="range" min="0" max="255" value="0" id="brightness">
<script>
var slider = document.getElementById("brightness");
var brightness = 0;
slider.oninput = function() {
brightness = this.value;
sendBrightness(brightness);
}
function sendBrightness(value) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/brightness?value=" + value, true);
xhr.send();
}
</script>
</body>
</html>
```
JavaScript 代码:
```javascript
var slider = document.getElementById("brightness");
var brightness = 0;
slider.oninput = function() {
brightness = this.value;
sendBrightness(brightness);
}
function sendBrightness(value) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "/brightness?value=" + value, true);
xhr.send();
}
```
ESP8266 代码:
```c++
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
// WiFi 参数
const char* ssid = "your-ssid";
const char* password = "your-password";
// 灯控制参数
const int LED_PIN = 5;
int brightness = 0;
// Web 服务器
ESP8266WebServer server(80);
void handleRoot() {
String html = "<html><head><title>ESP8266 LED Dimmer</title></head><body>";
html += "<h1>ESP8266 LED Dimmer</h1>";
html += "<input type=\"range\" min=\"0\" max=\"255\" value=\"";
html += String(brightness);
html += "\" id=\"brightness\">";
html += "<script>";
html += "var slider = document.getElementById(\"brightness\");";
html += "var brightness = " + String(brightness) + ";";
html += "slider.oninput = function() {";
html += "brightness = this.value;";
html += "sendBrightness(brightness);";
html += "}";
html += "function sendBrightness(value) {";
html += "var xhr = new XMLHttpRequest();";
html += "xhr.open(\"GET\", \"/brightness?value=\" + value, true);";
html += "xhr.send();";
html += "}";
html += "</script>";
html += "</body></html>";
server.send(200, "text/html", html);
}
void handleBrightness() {
String value = server.arg("value");
brightness = value.toInt();
analogWrite(LED_PIN, brightness);
server.send(200, "text/plain", "OK");
}
void setup() {
// 初始化串口
Serial.begin(9600);
// 连接 WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// 设置灯控制引脚
pinMode(LED_PIN, OUTPUT);
// 启动 Web 服务器
server.on("/", handleRoot);
server.on("/brightness", handleBrightness);
server.begin();
Serial.println("Web server started");
}
void loop() {
// 处理 Web 请求
server.handleClient();
}
```
将以上三段代码分别保存为 HTML、JavaScript 和 ESP8266 的 Arduino 代码,然后将 ESP8266 连接到电脑并烧录代码。最后,连接到 ESP8266 的 WiFi 热点,并在浏览器中输入 ESP8266 的 IP 地址,即可看到一个带有滑块控件的页面,用它来控制灯的亮度。
阅读全文