跑馬燈效果(RunningLights)
這段代碼用於實現 LED 燈條上顯示跑馬燈效果,即一組 LED 在燈條上以環形移動的視覺效果。下面我會詳細解釋這段代碼的每個部分及其工作原理。
函數介紹
void Running_light()
{
int running_ledcount = 10;
brightness = default_brightness;
strip.setBrightness(brightness);
for(int i = 0; i < strip.numPixels(); i++) { // 遍歷每個像素
if(i < running_ledcount)
{
strip.setPixelColor(LED_COUNT - running_ledcount + i, strip.Color(0, 0, 0)); // 關閉像素
}
else{
strip.setPixelColor(i - running_ledcount, strip.Color(0, 0, 0)); // 關閉像素
}
strip.setPixelColor(i, strip.Color(r, g, b)); // 設置紅色
strip.show();
delay(50);
}
}
這個函數的主要作用是實現 LED 燈在燈條上以環形移動的效果。它通過不斷更新燈條上 LED 的顏色來創造這種運動的感覺。
程式細節解釋
設定參數
int running_ledcount = 10; brightness = default_brightness; strip.setBrightness(brightness);
int running_ledcount = 10;:這個變量定義了參與跑馬燈效果的 LED 燈的數量。在這個例子中,10 個 LED 將同時點亮並移動。brightness = default_brightness;:這裡將亮度設置為預設值default_brightness。strip.setBrightness(brightness);:將亮度應用到燈條上,使所有 LED 的亮度設置為default_brightness。
遍歷像素並更新顏色
for(int i = 0; i < strip.numPixels(); i++) { // 遍歷每個像素
if(i < running_ledcount)
{
strip.setPixelColor(LED_COUNT - running_ledcount + i, strip.Color(0, 0, 0)); // 關閉像素
}
else{
strip.setPixelColor(i - running_ledcount, strip.Color(0, 0, 0)); // 關閉像素
}
strip.setPixelColor(i, strip.Color(r, g, b)); // 設置紅色
strip.show();
delay(50);
}
for(int i = 0; i < strip.numPixels(); i++):這個迴圈遍歷燈條上的每個 LED(從 0 到strip.numPixels()– 1)。strip.numPixels()是燈條上 LED 的總數。if(i < running_ledcount):這個條件判斷當前 LED 的索引i是否小於running_ledcount。如果是,則說明這個 LED 是處於跑馬燈的開頭部分,並需要在環形結束的地方進行處理。strip.setPixelColor(LED_COUNT - running_ledcount + i, strip.Color(0, 0, 0));:這行代碼關閉燈條上前一組 LED 燈中的一個,具體來說是位於LED_COUNT - running_ledcount + i的位置,這樣可以實現環形效果。
else:如果當前 LED 的索引i大於或等於running_ledcount,則執行以下代碼:strip.setPixelColor(i - running_ledcount, strip.Color(0, 0, 0));:這行代碼關閉目前 LED 的前一個 LED,確保只有running_ledcount個 LED 會保持點亮。
strip.setPixelColor(i, strip.Color(r, g, b));:這行代碼將當前的 LED 設置為紅色。變量r、g和b分別控制紅色、綠色和藍色的強度。strip.show();:這行代碼更新燈條顯示,將剛剛設定的顏色應用到 LED 上。delay(50);:每次更新後,程式會延遲 50 毫秒,這樣 LED 的移動速度會較為緩慢,形成流暢的跑馬燈效果。你可以調整這個值來加快或減慢跑馬燈的速度。
在程式中使用這個函數
#include <Adafruit_NeoPixel.h>
#define LED_PIN 6 // LED燈條連接的Arduino腳位
#define LED_COUNT 45 // LED燈的數量
#define default_brightness 30 // LED 預設亮度
uint8_t r = 255, g = 0, b = 0; // 初始顏色設為紅色
uint8_t brightness = default_brightness;
int running_ledcount = 10;
bool Breathing_effect_flag = 0;
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin(); // 初始化LED燈條
strip.show(); // 初始化所有LED為'關閉'狀態
strip.setBrightness(brightness); // 設置初始亮度
}
void loop() {
Running_light(); // 讓LED燈條顯示跑馬燈效果
}
void Running_light()
{
brightness = default_brightness;
strip.setBrightness(brightness);
for(int i = 0; i < strip.numPixels(); i++) { // 遍歷每個像素
if(i < running_ledcount)
{
strip.setPixelColor(LED_COUNT - running_ledcount + i, strip.Color(0, 0, 0)); // 關閉像素
}
else{
strip.setPixelColor(i - running_ledcount, strip.Color(0, 0, 0)); // 關閉像素
}
strip.setPixelColor(i, strip.Color(r, g, b)); // 設置紅色
strip.show();
delay(50);
}
}
