分享

Arduino教程 Lesson 13:彩灯调光台

 渔人 2018-10-04
Arduino教程 Lesson 6 -- 炫彩RGB LED中,我们已经接触过RGB LED了,可以实现变色,这回儿我们需要加入互动元素进去。通过三个电位器来任意变换对应的R、G、B,组合成任何你想要的颜色,在家做个心情灯吧,随心情任意切换。


所需材料
  • 1×  5mm RGB LED灯
  • 3×  220欧电阻
  • 3×  10K 电位器

STEP 1: 硬件连接



STEP 2: 输入代码
  1. int redPin = 9;                // R – digital 9   
  2. int greenPin = 10;             // G – digital 10
  3. int bluePin = 11;              // B – digital 11
  4. int potRedPin = 0;             // 电位器1 – analog 0
  5. int potGreenPin = 1;           // 电位器2 – analog 1
  6. int potBluePin = 2;            // 电位器3 – analog 2

  7. void setup(){
  8.     pinMode(redPin,OUTPUT);
  9.     pinMode(greenPin,OUTPUT);
  10.     pinMode(bluePin,OUTPUT);
  11.     Serial.begin(9600);           // 初始化串口
  12. }

  13. void loop(){
  14.    int potRed = analogRead(potRedPin);     // potRed存储模拟口0读到的值
  15.    int potGreen = analogRead(potGreenPin); // potGreen存储模拟口1读到的值
  16.    int potBlue = analogRead(potBluePin);  // potBlue存储模拟口2读到的值

  17.    int val1 = map(potRed,0,1023,0,255);     //通过map函数转换为0~255的值
  18.    int val2 = map(potGreen,0,1023,0,255);
  19.    int val3 = map(potBlue,0,1023,0,255);
  20.    
  21.    //串口依次输出Red,Green,Blue对应值
  22.    Serial.print("Red:");                  
  23.    Serial.print(val1);
  24.    Serial.print("Green:");
  25.    Serial.print(val2);
  26.    Serial.print("Blue:");
  27.    Serial.println(val3);
  28.    
  29.    colorRGB(val1,val2,val3);      // 让RGB LED 呈现对应颜色
  30. }

  31.   //该函数用于显示颜色
  32.   void colorRGB(int red, int green, int blue){     
  33.   analogWrite(redPin,constrain(red,0,255));
  34.   analogWrite(greenPin,constrain(green,0,255));
  35.   analogWrite(bluePin,constrain(blue,0,255));
  36. }
复制代码
下载代码,旋转三个电位器,可以变化出不同的颜色。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多