Hi. I wrote the code below to fade in and out the three colors on a rgb LED on three different "schedules" to get this nice sorta continuously changing color thing. It's working fine, but I was wondering if anyone has any ideas on perhaps making the fading routine into a function. I can see how to do it, except for the problem with updating the boolean flag. Can I have multiple return values? That would be great, but not sure if it's possible.
#define R_LED 11 // defining 3 pins for the 3 colors of the LED
#define G_LED 9
#define B_LED 10
int r = 0; // variables for brightness for each led
int g = 0;
int b = 0;
boolean r_dir = 1; // variables to flag for direction up or down
boolean g_dir = 1; // for fades
boolean b_dir = 1;
void setup() {
// nothing to setup
}
void loop() {
// loop, one per color for fades
if(r_dir) {
r = r + 3; // increment up
if (r >= 252) {
r_dir = 0; //change direction
}
}
else {
r = r - 3; // increment down
if (r <= 0) {
r_dir = 1; // change direction
}
}
// now for green
if(g_dir) {
g = g + 5; // increment up
if (g >= 250) {
g_dir = 0; //change direction
}
}
else {
g = g - 5; // increment down
if (g <= 0) {
g_dir = 1; // change direction
}
}
// and for blue
if(b_dir) {
b = b + 7; // increment up
if (b >= 248) {
b_dir = 0; //change direction
}
}
else {
b = b - 7; // increment down
if (b <= 0) {
b_dir = 1; // change direction
}
}
// now to write the values
analogWrite(R_LED, r);
analogWrite(G_LED, g);
analogWrite(B_LED, b);
delay(50);
}
You can't return multiple values from a function, but you could pass a single pointer to multiple parameters, using a structure, and a pointer to it into your function;
typedef struct {
int currentVal;
boolean direction;
byte increment;
byte LEDpin;
} colour_t;
colour_t red = {0, 1, 3, R_LED};
colour_t green = {yadda-yadda};
..
..
void update (colour_t* LED)
{
if (LED->direction)
etc, and so-on.
}
...
...
update (&red);
/*
This function will not return anything,
but will modify the values passed down as arguments
*/
void readAnalogValuesInto(int &pin1, int &pin2, int &pin3){
pin1 = analogRead(analogPin1);
pin2 = analogRead(analogPin2);
pin3 = analogRead(analogPin3);
}