搖桿+全彩LED燈 範例

 




const int redPin = 9;    // 紅色 LED
const int greenPin = 10; // 綠色 LED
const int bluePin = 11;  // 藍色 LED
//V 接 5V

const int joystickX = A0; // 搖桿 X 軸
const int joystickY = A1; // 搖桿 Y 軸
//5V 接 5V
//GND 接 GND

const int centerThreshold = 100; // 設定中立範圍

void setColor(int red, int green, int blue) {
    analogWrite(redPin, 255 - red);   // 反轉 PWM,適應共陽極 LED
    analogWrite(greenPin, 255 - green);
    analogWrite(bluePin, 255 - blue);
}

void setup() {
    pinMode(redPin, OUTPUT);
    pinMode(greenPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
    Serial.begin(9600);
}

void loop() {
    int xValue = analogRead(joystickX);
    int yValue = analogRead(joystickY);

    // 根據搖桿方向設定顏色
    if (xValue > 512 + centerThreshold) {
        setColor(255, 0, 0); // 右 → 紅色
    } else if (xValue < 512 - centerThreshold) {
        setColor(0, 255, 0); // 左 → 綠色
    } else if (yValue < 512 - centerThreshold) {
        setColor(0, 0, 255); // 上 → 藍色
    } else if (yValue > 512 + centerThreshold) {
        setColor(255, 165, 0); // 下 → 橙色
    } else {
        setColor(128, 0, 128); // 中立 → 紫色
    }

    Serial.print("X: ");
    Serial.print(xValue);
    Serial.print(" Y: ");
    Serial.println(yValue);

    delay(100);
}




留言