3. RGB LED颜色控制
任务目标
构建一个ESP32 Web服务器,用户通过浏览器中的颜色选择器选取颜色,ESP32接收后将其转换为PWM信号,驱动共阴RGB LED实现三色混色显示。
所需硬件与依赖
- ESP32开发板(如ESP32-DevKitC)
- 共阴RGB LED(红、绿、蓝三引脚+公共阴极)
- 3个220Ω限流电阻
- Arduino IDE(安装esp32开发板支持包)
电路连接
| RGB LED引脚 | ESP32引脚 |
|---|---|
| R(红) | GPIO 25 |
| G(绿) | GPIO 26 |
| B(蓝) | GPIO 27 |
| 阴极(最长引脚) | GND |
每个颜色引脚串联220Ω电阻后连接至对应GPIO。
完整代码
#include <WiFi.h>
#include <WebServer.h>
// WiFi配置
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
// RGB引脚定义
#define RED_PIN 25
#define GREEN_PIN 26
#define BLUE_PIN 27
// PWM参数
const int freq = 5000;
const int resolution = 8; // 0-255
WebServer server(80);
// 当前颜色值
int redVal = 0, greenVal = 0, blueVal = 0;
// HTML页面(内嵌颜色选择器)
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RGB LED控制</title>
</head>
<body style="text-align:center; font-family:Arial">
<h2>RGB LED 颜色控制</h2>
<input type="color" id="colorPicker" value="#ff0000" style="width:200px;height:100px;border:none">
<br><br>
<div id="hexDisplay" style="font-size:24px">#ff0000</div>
<script>
const picker = document.getElementById('colorPicker');
picker.addEventListener('input', function() {
const hex = this.value;
document.getElementById('hexDisplay').textContent = hex;
fetch('/color?hex=' + hex.substring(1));
});
</script>
</body>
</html>
)rawliteral";
void handleRoot() {
server.send(200, "text/html", index_html);
}
void handleColor() {
if (server.hasArg("hex")) {
String hex = server.arg("hex");
// 解析十六进制颜色值
long number = strtol(hex.c_str(), NULL, 16);
redVal = (number >> 16) & 0xFF;
greenVal = (number >> 8) & 0xFF;
blueVal = number & 0xFF;
// 更新PWM占空比
ledcWrite(0, redVal);
ledcWrite(1, greenVal);
ledcWrite(2, blueVal);
server.send(200, "text/plain", "OK");
} else {
server.send(400, "text/plain", "Missing hex parameter");
}
}
void setup() {
Serial.begin(115200);
// 配置PWM通道
ledcSetup(0, freq, resolution);
ledcSetup(1, freq, resolution);
ledcSetup(2, freq, resolution);
// 绑定引脚
ledcAttachPin(RED_PIN, 0);
ledcAttachPin(GREEN_PIN, 1);
ledcAttachPin(BLUE_PIN, 2);
// 初始关闭LED
ledcWrite(0, 0);
ledcWrite(1, 0);
ledcWrite(2, 0);
// 连接WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// 启动Web服务器
server.on("/", handleRoot);
server.on("/color", handleColor);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
运行与验证
- 将代码中的
your_SSID和your_PASSWORD替换为实际WiFi凭据。 - 按上述电路连接硬件,通过USB上传代码到ESP32。
- 打开Arduino IDE串口监视器(115200波特率),记录ESP32分配到的IP地址。
- 在浏览器中访问该IP地址,页面将显示颜色选择器。
- 拖动或点击颜色选择器选取任意颜色,RGB LED应立即显示对应颜色。
通过条件:LED实际发光颜色与网页中选取的颜色一致(允许轻微色差),且切换颜色时LED响应无延迟超过1秒。
常见问题
- LED不亮:检查是否为共阴LED(阴极接GND),若为共阳需将阴极接3.3V并反转PWM逻辑。
- 颜色偏差:不同LED亮度阈值不同,可在代码中调整
resolution或增加伽马校正。 - WiFi连接失败:确认SSID和密码正确,ESP32与路由器距离适中。