I’m attempting to be able to fade an RGB LED between various, named colours, using PWM (analoigWrite()) and arrays to hold the values for each RGB pin.
I had some troubles with this, getting the error [invalid types ‘int[int]’ for array subscript] until I came across this post on the forum, and the relevant answer:
PeterH:
The formal argument tab is an int. You are trying to treat it as an array of ints. An array is syntactically equivalent to a pointer to an array element, so change your declaration to void init_tableau (int *tab) and it should work.
I now have the problem of my values, in a for loop, going outside the bounds I had expected (i.e 0, 255) - possibly related to using pointers (which I don’t fully understand, but have some knowledge of).
In the code below (and the serial monitor section where the values get out of bounds), can anyone shed any light on how I should approach fixing this? Also, the overloaded for loop seems unwieldy to me, is there a better, more elegant way to approach this?
Many thanks.
int timer = 3000;
int redPin = 9;
int greenPin = 10;
int bluePin = 11;
int cyan[] = {0, 255, 255};
int purple[] = {100, 0, 255};
int colourName;
void setup() {
Serial.begin(9600);
}
void loop() {
fadeNamedColour(cyan, purple);
//delay(timer);
}
void fadeNamedColour(int *from, int *to) {
for (int redVal = from[0], greenVal = from[1], blueVal = from[2]; redVal < to[0], greenVal >= to[1], blueVal = to[2]; redVal++, greenVal--, blueVal++) {
analogWrite(redPin, redVal);
analogWrite(greenPin, greenVal);
analogWrite(bluePin, blueVal);
Serial.print("redVal = ");
Serial.print(redVal);
Serial.print("\t greenVal = ");
Serial.print(greenVal);
Serial.print("\t blueVal = ");
Serial.println(blueVal);
//delay(10);
}
}
void myColour(int *colourName) {
analogWrite(redPin, colourName[0]);
analogWrite(greenPin, colourName[1]);
analogWrite(bluePin, colourName[2]);
}
Serial monitor:
redVal = 15415 greenVal = -15160 blueVal = 255
redVal = 15416 greenVal = -15161 blueVal = 255
redVal = 15417 greenVal = -15162 blueVal = 255
redVal = 15418 greenVal = -15163 blueVal = 255
redVal = 15419 greenVal = -15164 blueVal = 255
redVal = 15420 greenVal = -15165 blueVal = 255
redVal = 15421 greenVal = -15166 blueVal = 255
redVal = 15422 greenVal = -15167 blueVal = 255