I got a problem with making a custom function on top of the FastLed library for Arduino.
The array of leds, structures called CRGB needs to be altered from inside the function drawGradient
to set the colors of the LEDs.
There must be something wrong with the pointers, references, parameters of the functions but I can't seem to figure out how to do it right. How to properly use the pointers/references for this piece of code?
Lines of interest
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);
}
Full code
#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;
}
Change you function signature:
void drawGradient(struct CRGB leds[], unsigned int from, unsigned int to, struct CRGB fromColor, struct CRGB toColor)
To
void drawGradient(struct CRGB *leds, unsigned int from, unsigned int to, struct CRGB fromColor, struct CRGB toColor)
And call the function drawGradient in the following way:
drawGradient(leds, 4, 0, CRGB::White, CRGB::Lime);
leds itself is the pointer of the array of CRGB structure. The &leds refers to the address of the pointer.