1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <Arduino.h>

#define RED_PIN 15
#define GREEN_PIN 2
#define BLUE_PIN 13

#define PWM_FREQ 5000 // 可依實體 LED 模組調整(避免閃爍)
#define PWM_RES 8

#define RED_CH 0
#define GREEN_CH 1
#define BLUE_CH 2

void setup() {
Serial.begin(115200);
Serial.println("RGB LED 測試開始(共陰)");

if (!ledcSetup(RED_CH, PWM_FREQ, PWM_RES)) Serial.println("❌ RED 設定失敗");
if (!ledcSetup(GREEN_CH, PWM_FREQ, PWM_RES)) Serial.println("❌ GREEN 設定失敗");
if (!ledcSetup(BLUE_CH, PWM_FREQ, PWM_RES)) Serial.println("❌ BLUE 設定失敗");

ledcAttachPin(RED_PIN, RED_CH);
ledcAttachPin(GREEN_PIN, GREEN_CH);
ledcAttachPin(BLUE_PIN, BLUE_CH);
}

void loop() {
setColor(255, 0, 0); delay(1000); // 紅
setColor(0, 255, 0); delay(1000); // 綠
setColor(0, 0, 255); delay(1000); // 藍
setColor(255, 255, 0); delay(1000); // 黃
setColor(0, 255, 255); delay(1000); // 青
setColor(255, 0, 255); delay(1000); // 紫
setColor(255, 255, 255); delay(1000); // 白
setColor(0, 0, 0); delay(1000); // 關
}

// 注意:此邏輯適用於共陰 RGB LED
void setColor(uint8_t r, uint8_t g, uint8_t b) {
ledcWrite(RED_CH, 255 - r);
ledcWrite(GREEN_CH, 255 - g);
ledcWrite(BLUE_CH, 255 - b);
}