Basics of coding: using an RGB LED with and without setColor function.

Hey everyone,

First of all, I’m going to try to do my best to describe my question. I’m going to try REALLY hard not to leave any openings for ambiguity. Please be gentle.

When programming an RBG LED on the Arduino, my inclination is to go one of two ways. If I just want the R, G and B to stay as regular colors, I pin them into regular (not analog) pins and use digitalWrite commands to make them HIGH or LOW. If I want to mix colors, I plug them into analog pins and use analogWrite commands with a number between 0 and 255 to control how dim I want them.

Yet I am having a hard time understanding how to mix colors, and when I look online, for instance at an adafruit tutorial found here (Overview | Arduino Lesson 3. RGB LEDs | Adafruit Learning System), it has this “setColor” function in it where you can mix the three values to make what’s essentially a color palette.

I think that’s nifty, and I can easily copy/paste the code and use it. But I’m trying to UNDERSTAND it. And in the Adafruit code there is this section which enables the whole thing to work:

void setColor(int red, int green, int blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

I have no idea how to even refer to this. I have only ever seen void setup and void loop. Yet here is void followed by setColor, and then a bunch of stuff is happening. My assumption is that this is a function is is being defined? Is that correct? “setColor” is not within the lexicon of Arduibo if I’m not mistaken. So what is this thing called, and how does this thing let the Arduino know that I can do a setColor(#1, #2, #3) command and actually understand it? I’ve been messing with analogWrite commands, but this seems much easier. I just want to understand it rather than just using it blindly.

Any help is much appreciated. Thank you all!

It is called a function and is named setColor. It takes 3 parameters, ie the values to be written to each LED

Some examples

Suppose you did

setColor(0, 0, 0);

Then 0 would be written to each of the LEDs

If you did

setColor(255, 0, 0);

then 255 would be written to the red LED and 0 to the others. I guess you know what sending 255 does

Can you guess what

setColor(255, 255, 255);

does ?

You can, of course, use it in a for loop like this

for (int r = 0; r < 256; r++)
{
    setColor(r, 0, 0);
    delay(100);
}