在使用安信可BW16-Kit来点亮RGB LED灯时,完成一系列步骤,确保硬件正确连接、环境配置妥当,并编写合适的代码来控制RGB LED灯的颜色和亮度。
先了解RGB LED灯的工作原理。RGB LED灯由红、绿、蓝三种颜色的LED芯片组成,通过调整每种颜色LED的亮度,可以混合出各种颜色。因此,您需要分别控制这三个颜色的LED芯片。
硬件连接:
请注意,根据RGB LED灯的类型和规格,您可能需要在LED灯与GPIO引脚之间添加适当的限流电阻,以防止电流过大损坏LED灯或BW16-Kit。
原理图:
#define LED_R PA12 // 红色LED连接的引脚
#define LED_G PA14 // 绿色LED连接的引脚
#define LED_B PA13 // 蓝色LED连接的引脚
void setup() {
pinMode(LED_R, OUTPUT);
pinMode(LED_G, OUTPUT);
pinMode(LED_B, OUTPUT);
}
void loop() {
// 显示红色
digitalWrite(LED_R, HIGH);
digitalWrite(LED_G, LOW);
digitalWrite(LED_B, LOW);
delay(1000); // 等待一秒
// 显示绿色
digitalWrite(LED_R, LOW);
digitalWrite(LED_G, HIGH);
digitalWrite(LED_B, LOW);
delay(1000); // 等待一秒
// 显示蓝色
digitalWrite(LED_R, LOW);
digitalWrite(LED_G, LOW);
digitalWrite(LED_B, HIGH);
delay(1000); // 等待一秒
// 重复上述过程
}
实现的代码:
void setup() {
// initialize digital pin's from all 3 colors as an output.
pinMode(LED_R, OUTPUT);
pinMode(LED_G, OUTPUT);
pinMode(LED_B, OUTPUT);
}
// blink RED, GREEN, BLUE
void blink() {
digitalWrite(LED_R, HIGH); // turn the RED LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_R, LOW); // h:\Evaluation\BW16 KIT\led\led\led.inoturn the RED LED off by making the voltage LOW
delay(1000); // wait for a second
digitalWrite(LED_G, HIGH); // turn the GREEN LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_G, LOW); // turn the GREEN LED off by making the voltage LOW
delay(1000); // wait for a second
digitalWrite(LED_B, HIGH); // turn the BLUE LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_B, LOW); // turn the BLUE LED off by making the voltage LOW
delay(1000); // wait for a second
}
// fade RED and BLUE
void fade() {
// fade RED in from min to max in increments of 5 points:
for (int fadeValue = 0; fadeValue <= 255; fadeValue += 5) {
// sets the value (range from 0 to 255):
analogWrite(LED_R, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade RED out from max to min in increments of 5 points:
for (int fadeValue = 255; fadeValue >= 0; fadeValue -= 5) {
// sets the value (range from 0 to 255):
analogWrite(LED_R, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade BLUE in from min to max in increments of 5 points:
for (int fadeValue = 0; fadeValue <= 255; fadeValue += 5) {
// sets the value (range from 0 to 255):
analogWrite(LED_B, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
// fade BLUE out from max to min in increments of 5 points:
for (int fadeValue = 255; fadeValue >= 0; fadeValue -= 5) {
// sets the value (range from 0 to 255):
analogWrite(LED_B, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
// the loop function runs over and over again forever
void loop() {
blink(); // blink RED, GREEN, BLUE
fade(); // fade RED, BLUE
delay(1000); // wait for a second
}
上传与测试:
实际显示效果: