需要自己更改WiFi名称和密码
使用说明
-
将上述代码上传到Arduino R4 WiFi
-
修改代码中的
YourWiFiSSID
和YourWiFiPassword
为您的WiFi凭据 -
根据实际连接修改
redPin
,greenPin
,bluePin
的引脚号 -
打开串口监视器查看Arduino的IP地址
-
在浏览器中输入该IP地址,会出现一个控制页面
-
使用滑块调整RGB值并点击"Set Color"按钮
注意事项
-
如果使用共阴极RGB LED,需要将
analogWrite
的值直接设置为输入值(去掉255-) -
确保RGB LED的每个通道都连接了适当的限流电阻(通常220Ω)
-
根据RGB LED的规格选择正确的电压(3.3V或5V)
扩展功能
如果需要更高级的控制,可以考虑:
-
添加颜色选择器(使用HTML5的color input)
-
实现渐变效果
-
添加预设颜色按钮
-
使用WebSocket实现实时更新而不需要刷新页面
#include <WiFiS3.h>
// 设置WiFi凭据
const char* ssid = "YourWiFiSSID";
const char* password = "YourWiFiPassword";
// 设置RGB引脚
const int redPin = 9;
const int greenPin = 10;
const int bluePin = 11;
WiFiServer server(80);
void setup() {
Serial.begin(9600);
while (!Serial);
// 设置RGB引脚为输出
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
// 初始关闭LED
analogWrite(redPin, 255);
analogWrite(greenPin, 255);
analogWrite(bluePin, 255);
// 连接WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
Serial.println("New client connected");
String currentLine = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
if (c == '\n') {
if (currentLine.length() == 0) {
// 发送HTTP响应头
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// 发送HTML页面
client.println("<html><head><title>RGB LED Control</title></head><body>");
client.println("<h1>RGB LED Control</h1>");
client.println("<form method='get'>");
client.println("Red (0-255): <input type='range' name='r' min='0' max='255'><br>");
client.println("Green (0-255): <input type='range' name='g' min='0' max='255'><br>");
client.println("Blue (0-255): <input type='range' name='b' min='0' max='255'><br>");
client.println("<input type='submit' value='Set Color'>");
client.println("</form>");
client.println("</body></html>");
break;
} else {
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
// 检查是否有颜色设置请求
if (currentLine.startsWith("GET /?r=")) {
// 解析RGB值
int redIndex = currentLine.indexOf("r=");
int greenIndex = currentLine.indexOf("g=");
int blueIndex = currentLine.indexOf("b=");
int redValue = currentLine.substring(redIndex + 2, greenIndex - 1).toInt();
int greenValue = currentLine.substring(greenIndex + 2, blueIndex - 1).toInt();
int blueValue = currentLine.substring(blueIndex + 2).toInt();
// 设置LED颜色
analogWrite(redPin, 255 - redValue); // 共阳极需要反向
analogWrite(greenPin, 255 - greenValue);
analogWrite(bluePin, 255 - blueValue);
Serial.print("Set RGB to: ");
Serial.print(redValue);
Serial.print(", ");
Serial.print(greenValue);
Serial.print(", ");
Serial.println(blueValue);
}
}
}
client.stop();
Serial.println("Client disconnected");
}
}