如何从ESP8266网页jscolor提取RGB值传入Arduino代码
解决ESP8266接收jscolor RGB值的方案
我来帮你搞定把jscolor选择的RGB值传回ESP8266的问题,咱们分前端HTML和后端Arduino代码两部分修改,步骤很清晰:
1. 修改前端 index.html 代码
我们需要在颜色选择器的回调函数里,把RGB值通过HTTP请求发送给ESP8266。直接在你现有的update函数里添加发送逻辑就行,这样每次颜色微调(或者确认)时都会同步数据:
<!DOCTYPE html> <html> <head> <title>Getting colors</title> </head> <body> <script src="jscolor.js"></script> <div style="position:absolute; left:280px; top:10px;"> toHEXString = <span id="hex-str"></span><br /> toRGBString = <span id="rgb-str"></span><br /> R, G, B = <span id="rgb"></span><br /> H, S, V = <span id="hsv"></span> </div> <input class="jscolor {onFineChange:'update(this)'}" value="ffcc00"> <script> function update(picker) { // 原有页面更新逻辑保留 document.getElementById('hex-str').innerHTML = picker.toHEXString(); document.getElementById('rgb-str').innerHTML = picker.toRGBString(); const r = Math.round(picker.rgb[0]); const g = Math.round(picker.rgb[1]); const b = Math.round(picker.rgb[2]); document.getElementById('rgb').innerHTML = r + ', ' + g + ', ' + b; document.getElementById('hsv').innerHTML = Math.round(picker.hsv[0]) + '°, ' + Math.round(picker.hsv[1]) + '%, ' + Math.round(picker.hsv[2]) + '%'; // 新增:发送RGB数据到ESP8266的/sendRGB端点 fetch(`/sendRGB?r=${r}&g=${g}&b=${b}`) .then(response => response.text()) .catch(err => console.log('发送数据出错:', err)); } </script> </body> </html>
如果不想实时发送(只在用户确认颜色时发送),可以把onFineChange改成onChange,这样只有用户点击确认按钮或者选择完颜色后才会触发请求。
2. 修改Arduino代码
接下来要在ESP8266的WebServer里添加一个处理器,接收前端发来的RGB参数并保存为全局变量,方便后续使用:
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WiFiMulti.h> #include <ESP8266mDNS.h> #include <ESP8266WebServer.h> #include <FS.h> ESP8266WiFiMulti wifiMulti; ESP8266WebServer server(80); File fsUploadFile; String getContentType(String filename); bool handleFileRead(String path); void handleFileUpload(); // 新增:全局变量存储RGB值,初始值对应你设置的ffcc00 int currentR = 255; int currentG = 204; int currentB = 0; void setup() { Serial.begin(115200); delay(10); Serial.println('\n'); wifiMulti.addAP("itsveryeasy", "samepassword"); wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2"); wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3"); Serial.println("Connecting ..."); int i = 0; while (wifiMulti.run() != WL_CONNECTED) { delay(1000); Serial.print(++i); Serial.print(' '); } Serial.println('\n'); Serial.print("Connected to "); Serial.println(WiFi.SSID()); Serial.print("IP address:\t"); Serial.println(WiFi.localIP()); if (!MDNS.begin("esp8266")) { Serial.println("Error setting up MDNS responder!"); } Serial.println("mDNS responder started"); SPIFFS.begin(); server.on("/upload", HTTP_GET, []() { if (!handleFileRead("/upload.html")) server.send(404, "text/plain", "404: Not Found"); }); server.on("/upload", HTTP_POST, [](){ server.send(200); }, handleFileUpload ); // 新增:处理RGB数据的请求端点 server.on("/sendRGB", HTTP_GET, []() { // 检查是否所有参数都存在 if (server.hasArg("r") && server.hasArg("g") && server.hasArg("b")) { // 把参数转换成整数并更新全局变量 currentR = server.arg("r").toInt(); currentG = server.arg("g").toInt(); currentB = server.arg("b").toInt(); // 串口打印调试,方便查看数据 Serial.print("Received RGB: "); Serial.print(currentR); Serial.print(", "); Serial.print(currentG); Serial.print(", "); Serial.println(currentB); // 返回成功响应给前端 server.send(200, "text/plain", "RGB values updated"); } else { // 参数不全时返回错误 server.send(400, "text/plain", "Missing RGB parameters"); } }); server.onNotFound([]() { if (!handleFileRead(server.uri())) server.send(404, "text/plain", "404: Not Found"); }); server.begin(); Serial.println("HTTP server started"); } void loop() { server.handleClient(); // 这里可以添加你的业务逻辑,比如用currentR/G/B控制LED // 示例:analogWrite(LED_R_PIN, currentR); // analogWrite(LED_G_PIN, currentG); // analogWrite(LED_B_PIN, currentB); } // 以下原有函数无需修改 String getContentType(String filename) { if (filename.endsWith(".html")) return "text/html"; else if (filename.endsWith(".css")) return "text/css"; else if (filename.endsWith(".js")) return "application/javascript"; else if (filename.endsWith(".ico")) return "image/x-icon"; else if (filename.endsWith(".gz")) return "application/x-gzip"; return "text/plain"; } bool handleFileRead(String path) { Serial.println("handleFileRead: " + path); if (path.endsWith("/")) path += "index.html"; String contentType = getContentType(path); String pathWithGz = path + ".gz"; if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { if (SPIFFS.exists(pathWithGz)) path += ".gz"; File file = SPIFFS.open(path, "r"); size_t sent = server.streamFile(file, contentType); file.close(); Serial.println(String("\tSent file: ") + path); return true; } Serial.println(String("\tFile Not Found: ") + path); return false; } void handleFileUpload(){ HTTPUpload& upload = server.upload(); if(upload.status == UPLOAD_FILE_START){ String filename = upload.filename; if(!filename.startsWith("/")) filename = "/"+filename; Serial.print("handleFileUpload Name: "); Serial.println(filename); fsUploadFile = SPIFFS.open(filename, "w"); filename = String(); } else if(upload.status == UPLOAD_FILE_WRITE){ if(fsUploadFile) fsUploadFile.write(upload.buf, upload.currentSize); } else if(upload.status == UPLOAD_FILE_END){ if(fsUploadFile) { fsUploadFile.close(); Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize); server.sendHeader("Location","/success.html"); server.send(303); } else { server.send(500, "text/plain", "500: couldn't create file"); } } }
测试方法
- 把修改后的
index.html上传到ESP8266的SPIFFS中; - 上传修改后的Arduino代码到ESP8266;
- 打开串口监视器,查看ESP8266的IP地址;
- 在浏览器中访问该IP地址,调整颜色选择器,此时串口监视器会实时打印收到的RGB值;
- 之后你就可以在
loop函数里使用currentR、currentG、currentB这三个变量来控制LED或其他外设了。
内容的提问来源于stack exchange,提问作者user1543571
相关产品推荐
相关产品推荐

