ARDUINO – 摇杆与RGB灯

2022/08 20 14:08

GND、VCC(+5V)分别接地和VCC电源口

VRx,VRy (X、Y轴)为模拟输入信号,连接到模拟IO口A0~A7,从 0 ~ 1023 分别代表 左~右,上~下。中间值为512

SW (Z轴)是数字输入信号,连接到数字端口,并启用上拉电阻,SW 的值:1代表未按下,0代表按下。

#define RGB_RED    9
#define RGB_GREEN  10
#define RGB_BLUE   11

void setup()
{
    Serial.begin(9600);
    pinMode(7, INPUT_PULLUP);
    pinMode(RGB_RED,OUTPUT);
    pinMode(RGB_GREEN,OUTPUT);
    pinMode(RGB_BLUE,OUTPUT);
}

void setColor(int red,int blue, int green)
{
    analogWrite(RGB_RED,red);
    analogWrite(RGB_GREEN,green);
    analogWrite(RGB_BLUE,blue);
}

void loop()
{
    int r = 512 - analogRead(A0);
    int g = 512 - analogRead(A1);
    if ( digitalRead(7) == 0 )
    {
      setColor(0, 0, 255);
    }
    else
    {
      Serial.print(r, DEC);
      Serial.print(",");
      Serial.print(g, DEC);
      Serial.print("\r\n");
      r = abs(r);
      g = abs(g);
      setColor(r, g, 0);
    }
    delay(1);
}

--转载请注明: http://blog.coolcoding.cn/?p=4491