我是基于arduino UNO R3套件来实现的RGB三色灯案例。在这整套的套件中,备有RGB三色灯集成器件。
关于RGB三色灯的电路原理,各位直接在网上就可以搜索到,这里就不过多赘述。接下来就是关于RGB三色灯的实例。程序实例和端口请根据实际情况进行调整。
RGB三色灯——流水灯效果:
#define RED 12 #define GREEN 8 #define BLUE 7 void red(void); void green(void); void blue(void); void setup() { // put your setup code here, to run once: pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); digitalWrite(RED, LOW); digitalWrite(RED, LOW); digitalWrite(RED, LOW); } void loop() { // put your main code here, to run repeatedly: red(); delay(1000); green(); delay(1000); blue(); delay(1000); } void red(void) { digitalWrite(RED, HIGH); digitalWrite(GREEN, LOW); digitalWrite(BLUE, LOW); } void green(void) { digitalWrite(RED, LOW); digitalWrite(GREEN, HIGH); digitalWrite(BLUE, LOW); } void blue(void) { digitalWrite(RED, LOW); digitalWrite(GREEN, LOW); digitalWrite(BLUE, HIGH); }
RGB三色灯——呼吸灯效果:
#define LED_red 11 #define LED_green 10 #define LED_blue 9 void breath(int pin); void setup() { // put your setup code here, to run once: pinMode(LED_red, OUTPUT); pinMode(LED_green, OUTPUT); pinMode(LED_blue, OUTPUT); } void loop() { // put your main code here, to run repeatedly: breath(LED_red); breath(LED_green); breath(LED_blue); } void breath(int pin) { for(int i = 0; i <= 255; i++) { analogWrite(pin, i); delay(5); } for(int i = 255; i >= 0; i--) { analogWrite(pin, i); delay(5); } delay(100); }
这里要提醒一下各位:在Arduino UNO板上,有pwm输出口,需要各位注意看,并且在这里我是用到了analogWrite(int pin, int value)函数,是arduino函数库中专门用来pwm调试输出的。