一.简介
通过按键控制RGB灯分别显示7种颜色:红 、绿、 蓝、 黄、 青、 紫、 白。
二.按键控制RGB灯原理
1)RGB全彩LED:
LED由三个颜色分别为:红(Red)、绿(Green)、蓝(Blue)的LED组成,通过调整3个LED的亮度,就可以产生不同的颜色。
2)三种基色组合成七色光:
黄色:红色+绿色
青色:绿色+蓝色
紫色:红色+蓝色
白色:红色+绿色+蓝色
三.源代码
#define redLED 7
#define greenLED 8
#define blueLED 9
#define KEY 2
//枚举定义7种颜色:红 绿 蓝 黄 青 紫 白
enum{redColor,greenColor,blueColor,yellowColor,qingColor,purpleColor,whiteColor};
unsigned int num = 0;
void setup() {// put your setup code here, to run once:pinMode(KEY,INPUT_PULLUP);//设置输入上拉模式pinMode(redLED,OUTPUT);pinMode(greenLED,OUTPUT);pinMode(blueLED,OUTPUT);digitalWrite(redLED,LOW);digitalWrite(greenLED,LOW);digitalWrite(blueLED,LOW);
}void loop() {// put your main code here, to run repeatedly:if(isKeyPress()){if(num == 7)num = 0;switch(num){case redColor:redBright();break;case greenColor:greenBright();break;case blueColor:blueBright();break;case yellowColor:yellowBright();break;case qingColor:qingBright();break;case purpleColor:purpleBright();break;case whiteColor:whiteBright();break;}num++;}
}//红色
void redBright()
{//高电平点亮相应的灯digitalWrite(redLED,HIGH);digitalWrite(greenLED,LOW);digitalWrite(blueLED,LOW);
}
//绿色
void greenBright()
{digitalWrite(redLED,LOW);digitalWrite(greenLED,HIGH);digitalWrite(blueLED,LOW);
}
//蓝色
void blueBright()
{digitalWrite(redLED,LOW);digitalWrite(greenLED,LOW);digitalWrite(blueLED,HIGH);
}
//黄色
void yellowBright()
{digitalWrite(redLED,HIGH);digitalWrite(greenLED,HIGH);digitalWrite(blueLED,LOW);
}
//青色
void qingBright()
{digitalWrite(redLED,LOW);digitalWrite(greenLED,HIGH);digitalWrite(blueLED,HIGH);
}
//紫色
void purpleBright()
{digitalWrite(redLED,HIGH);digitalWrite(greenLED,LOW);digitalWrite(blueLED,HIGH);
}
//白色
void whiteBright()
{digitalWrite(redLED,HIGH);digitalWrite(greenLED,HIGH);digitalWrite(blueLED,HIGH);
}bool isKeyPress()
{if(digitalRead(KEY) == LOW){delay(20);//延迟消抖if(digitalRead(KEY) == LOW){while(1){//按键松开if(digitalRead(KEY) == HIGH)return true;}}}return false;
}