2016-12-07 132 views
1

我想做一個循環,觸發我聲明的數組列表。但目前似乎沒有任何工作。如何在Arduino上循環變量名?

目標是讓循環在Neopixels上創建動畫。數組是該動畫的關鍵幀,我知道,可能有更好和更有效的方法來做到這一點。但這可能會符合我的要求。

所以,我已經嘗試過這樣既:

const int startSwipe0[][4] = {whole list of numbers}; 
const int startSwipe1[][4] = {whole list of numbers}; 
const int startSwipe2[][4] = {whole list of numbers}; 
const int startSwipe3[][4] = {whole list of numbers}; 
const int startSwipe4[][4] = {whole list of numbers}; 
const int startSwipe5[][4] = {whole list of numbers}; 

void setup() { 
    strip.begin(); 
    strip.setBrightness(100); // 0-255 brightness 
    strip.show();    // Initialize all pixels to 'off' 
} 

void loop() { 
    currentTime = millis(); 
    animation_a(); 
    strip.show(); 
} 

void animation_a() { 
    for (int j=0; j<6; j++) { 
    for (int i=0; i<NUM_LEDS; i++) { 
     String swipeInt = String(j); 
     String swipeName = "startSwipe"+swipeInt; 
     Serial.println(swipeName); 
     strip.setPixelColor(i, swipeName[i][1], swipeName[i][2], swipeName[i][3]); 
    } 
    } 
} 

但這給出了這樣的錯誤「無效類型‘的char [INT]’數組下標」,但它並打印相同的名字作爲我的數組名稱。

請幫忙!謝謝!

+0

這種方法是一種適合一些腳本語言,但Arduino是*編譯*。一旦程序運行,諸如變量名稱之類的東西就絕對沒有意義,這樣的名字就在你和編譯器之間。 – unwind

回答

1

您應該將您的動畫聲明爲二維數組,而不是單獨的數組。這樣,你可以用兩個for循環遍歷它們。

有一個NeoPixel函數,可以將RGB值存儲爲32位整數。假設你有三個LED,你想控制你的帶(爲了簡單起見)。我們在動畫中聲明四個「關鍵幀」。我們將從紅色到綠色,再到藍色,再到白色。

#include <Adafruit_NeoPixel.h> 

#define PIN 6 
#define LEDS 3 

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDS, PIN, NEO_GRB + NEO_KHZ800); 

// Define animation 
#define FRAMES 4 
uint32_t animation[FRAMES][LEDS] = { 
    {strip.Color(255, 0, 0), strip.Color(255, 0, 0), strip.Color(255, 0, 0)}, 
    {strip.Color(0, 255, 0), strip.Color(0, 255, 0), strip.Color(0, 255, 0)}, 
    {strip.Color(100, 100, 100), strip.Color(100, 100, 100), strip.Color(100, 100, 100)} 
}; 

void setup() { 
    strip.begin(); 
    strip.show(); 
} 

void loop() { 
    // Play the animation, with a small delay 
    playAnimation(100); 
} 

void playAnimation(int speed) { 
    for(int j=0; j<FRAMES; j++) { 
    // Set colour of LEDs in this frame of the animation. 
    for(int i=0; i<LEDS; i++) strip.setPixelColor(i, animation[j][i]); 
    strip.show(); 
    // Wait a little, for the frame to be seen by humans. 
    delay(speed); 
    } 
} 

正如你所看到的,明確定義動畫有點笨拙。這就是爲什麼大多數人寫一個定製的算法來執行他們想要的動畫類型。代碼更輕,更快更快。但嘿嘿,如果它適合你,那麼我是誰來阻止你!

來源:https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library