0

在 Arduino 的FastLed库之上创建自定义函数时遇到问题。

需要从函数内部更改LED 阵列、称为 CRGB 的结构drawGradient以设置 LED 的颜色。

函数的指针、引用、参数肯定有问题,但我似乎无法弄清楚如何正确处理。如何正确使用这段代码的指针/引用?

兴趣线

CRGB leds[NUM_LEDS];

void loop() {
    drawGradient(&leds, 4, 0, CRGB::White, CRGB::Lime);
}

void drawGradient(struct CRGB leds[], unsigned int from, unsigned int to, struct CRGB fromColor, struct CRGB toColor) {
    leds[j] = pickFromGradient(fromColor, fromColor, position);
}

完整代码

#include "FastLED.h"

#define NUM_LEDS 18

#define DATA_PIN 7

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
}

void loop() {
  leds[4] = CRGB::Red;
  FastLED.show();

  delay(1000);

  drawGradient(&leds, 4, 0, CRGB::White, CRGB::Lime);
  drawGradient(&leds, 4, 8, CRGB::White, CRGB::Lime);
  drawGradient(&leds, 13, 9, CRGB::White, CRGB::Lime);
  drawGradient(&leds, 13, 17, CRGB::White, CRGB::Lime);

  FastLED.show();

  while(1); // Save energy :-)
}

void drawGradient(struct CRGB leds[], unsigned int from, unsigned int to, struct CRGB fromColor, struct CRGB toColor) {
  unsigned int barLength = abs(to - from) + 1;
  int rangePerPixel = 255/barLength;

  for(int i = 0; i <= barLength; i++) {
    int j = 0;
    if(from < to) {
      j = from + i;
    } else {
      j = max(from, to) - i;
    }

    float position = i / barLength;

    leds[j] = pickFromGradient(fromColor, toColor, position);
  }
}

struct CRGB pickFromGradient(struct CRGB fromColor, struct CRGB toColor, float position) {
  struct CRGB newColor;

  uint8_t r = fromColor.r + position * (toColor.r - fromColor.r);
  uint8_t g = fromColor.g + position * (toColor.g - fromColor.g);
  uint8_t b = fromColor.b + position * (toColor.b - fromColor.b);

  newColor.setRGB(r, g, b);

  return newColor;
}
4

2 回答 2

2

改变你的功能签名:

  void drawGradient(struct CRGB leds[], unsigned int from, unsigned int to, struct CRGB fromColor, struct CRGB toColor)

void drawGradient(struct CRGB *leds, unsigned int from, unsigned int to, struct CRGB fromColor, struct CRGB toColor)

并通过以下方式调用函数drawGradient:

  drawGradient(leds, 4, 0, CRGB::White, CRGB::Lime);

leds 本身就是 CRGB 结构数组的指针。&leds 指的是指针的地址。

于 2014-10-14T20:02:37.713 回答
0

使用相同的颜色调用 pickFromGradient:

leds[j] = pickFromGradient(fromColor, fromColor, position);

应该:

leds[j] = pickFromGradient(fromColor, toColor, position);
于 2014-10-14T20:12:48.383 回答