用按鈕切換七彩燈

 //用按鈕切換七彩燈

// 共陽極 RGB LED 腳位 

#define RED_PIN 9

#define GREEN_PIN 10

#define BLUE_PIN 11


// 按鈕腳位

#define BUTTON_PIN 2


int currentColor = 0;  // 紀錄目前顏色編號 (0~6)


// 彩虹七色 (紅、橙、黃、綠、藍、靛、紫)

int rainbowColors[7][3] = {

  {255, 0, 0},     // 紅

  {255, 127, 0},   // 橙

  {255, 255, 0},   // 黃

  {0, 255, 0},     // 綠

  {0, 0, 255},     // 藍

  {75, 0, 130},    // 靛

  {148, 0, 211}    // 紫

};


void setup() {

  pinMode(RED_PIN, OUTPUT);

  pinMode(GREEN_PIN, OUTPUT);

  pinMode(BLUE_PIN, OUTPUT);

  pinMode(BUTTON_PIN, INPUT_PULLUP); // 使用內建上拉電阻

}


void loop() {

  // 偵測按鈕是否按下

  if (digitalRead(BUTTON_PIN) == LOW) {

    delay(200); // 簡單防彈跳

    currentColor = (currentColor + 1) % 7; // 切換到下一個顏色

    setColor(rainbowColors[currentColor][0],

             rainbowColors[currentColor][1],

             rainbowColors[currentColor][2]);

    while (digitalRead(BUTTON_PIN) == LOW); // 等待放開按鈕

  }

}


void setColor(int red, int green, int blue) {

  // 共陽極 → PWM 值要反轉

  analogWrite(RED_PIN, 255 - red);

  analogWrite(GREEN_PIN, 255 - green);

  analogWrite(BLUE_PIN, 255 - blue);

}


留言