RGB LED 有四支腳,我們所用的模組為共陰極,陰極腳接地,其他三支腳位分別控制 R、G、B 色彩。 以下的電路示意與第一段程式碼,示範情境為:以 digitalWrite 對三個顏色的腳位給予不同電位,產生不同的顏色組合。 電路示意圖 範例程式 int red_led = 11;int gree_led = 10;int blue_led = 9;void setup() { pinMode(red_led, OUTPUT); pinMode(gree_led, OUTPUT); pinMode(blue_led, OUTPUT);}void loop() { //0 black digitalWrite(red_led, LOW); digitalWrite(gree_led, LOW); digitalWrite(blue_led, LOW); delay(1000); //1 red digitalWrite(red_led, HIGH); digitalWrite(gree_led, LOW); digitalWrite(blue_led, LOW); delay(1000); //2 gree digitalWrite(red_led, LOW); digitalWrite(gree_led, HIGH); digitalWrite(blue_led, LOW); delay(1000); //3 yellow digitalWrite(red_led, HIGH); digitalWrite(gree_led, HIGH); digitalWrite(blue_led, LOW); delay(1000); //4 blue digitalWrite(red_led, LOW); digitalWrite(gree_led, LOW); digitalWrite(blue_led, HIGH); delay(1000); //5 purple digitalWrite(red_led, HIGH); digitalWrite(gree_led, LOW); digitalWrite(blue_led, HIGH); delay(1000); //6 Cyan digitalWrite(red_led, LOW); digitalWrite(gree_led, HIGH); digitalWrite(blue_led, HIGH); delay(1000); //7 white digitalWrite(red_led, HIGH); digitalWrite(gree_led, HIGH); digitalWrite(blue_led, HIGH); delay(1000);} 程式碼二 以迴圈和 analogWrite() 產生三色輪動之燈光明滅的效果(呼吸燈) const int led[] = {11, 10, 9};int pinCount = sizeof(led) / sizeof(int);int brightness = 0;int lightenstep = 5;int direct = 1;int DEBUG = 1;int delayTime = 50;void setup() { for (int pin = 0 ; pin < pinCount; pin++) { pinMode(led[pin], OUTPUT); analogWrite(led[pin], brightness); } Serial.begin(9600);}void loop() { int pin = 0; while (pin < pinCount) { if (DEBUG) { Serial.print("=== Using Pin: "); Serial.print(led[pin]); Serial.println(" ==="); } breath(pin); pin++; delay(delayTime); }}void breath(int ledNums) { for (int i = 0; i < 255; i += lightenstep) { brightness += lightenstep; analogWrite(led[ledNums], brightness); if (DEBUG) { Serial.println(brightness); } delay(delayTime); } for (int j = 255; j > 0; j -= lightenstep) { brightness -= lightenstep; analogWrite(led[ledNums], brightness); if (DEBUG) { Serial.println(brightness); } delay(delayTime); }} 思考練習 程式碼二中,其三色輪動的效果是 1 -> 2 -> 3 -> 1 -> 2 -> 3…,若我們想改為來回的方式輪動顏色 1 -> 2 -> 3 -> 2 -> 1 -> 2 -> 3…,應該如何修改程式碼呢?請試著實作看看。 請參考下圖,實作來回閃爍燈效果
Comments