如何在Arduino上循环变量名?

时间:2016-12-07 10:53:00

标签: arrays loops variables 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]'”,但它确实打印了与我的数组名称相同的名称。

请帮忙!谢谢!

1 个答案:

答案 0 :(得分: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