2016-12-07 51 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