最新消息:

Arduino教程 Lesson 13– 彩灯调光台

Arduino 少儿编程 1929浏览 0评论
Arduino初级教程
该教程实验平台:Arduino入门套件

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


所需材料

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

STEP 1: 硬件连接

Arduino教程 Lesson 13-- 彩灯调光台

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.    //串口依次输出Red,Green,Blue对应值
  21.    Serial.print(“Red:”);
  22.    Serial.print(val1);
  23.    Serial.print(“Green:”);
  24.    Serial.print(val2);
  25.    Serial.print(“Blue:”);
  26.    Serial.println(val3);
  27.    colorRGB(val1,val2,val3);      // 让RGB LED 呈现对应颜色
  28. }
  29.   //该函数用于显示颜色
  30.   void colorRGB(int red, int green, int blue){
  31.   analogWrite(redPin,constrain(red,0,255));
  32.   analogWrite(greenPin,constrain(green,0,255));
  33.   analogWrite(bluePin,constrain(blue,0,255));
  34. }

复制代码

下载代码,旋转三个电位器,可以变化出不同的颜色。

您必须 登录 才能发表评论!