Thursday, 31 December 2009

RGB LED

As I said in my previous post, those good people at oomlout sent me a free RGB LED sample so I felt it would be daft to to have a good play with it.
Following the circuit diagram on the piece of paper and using the three resistors taped to the back I built this lovely little bit of gizmometry:










Using the following code I set the the LED to flash red, then green, then blue.


/**
* RGB LED test
*/

int redLed = 11;
int greenLed = 12;
int blueLed = 13;

const boolean ON = LOW;
const boolean OFF = HIGH;

const boolean RED[] = {ON, OFF, OFF};
const boolean GREEN[] = {OFF, ON, OFF};
const boolean BLUE[] = {OFF, OFF, ON};


void setup()
{
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(blueLed, OUTPUT);
}

void loop()
{
setColour(RED);
delay (100);
setColour(GREEN);
delay (100);
setColour(BLUE);
delay (100);
}

void setColour(const boolean* colour)
{
digitalWrite (redLed, colour[0]);
digitalWrite (greenLed, colour[1]);
digitalWrite (blueLed, colour[2]);
}


Now this is all well and good, but it isn't very interactive is it? So I decided to add a potentiometer to the circuit and feel the output of the pot to the analogue in of the Arduino, the idea being to control the colour of the LED using the pot.
I also decided that red, green and blue were just too boring, so I also added the secondary colours yellow, cyan and magenta as these can be created by simply mixing red, green and blue.

Then with the following code we read the value of the potentiometer and set the colour accordingly.

/**
* RGB LED test version 2
*/

int redLed = 11;
int greenLed = 12;
int blueLed = 13;
int potPin = 0;
int potValue = 0;

const boolean ON = LOW;
const boolean OFF = HIGH;

const boolean RED[] = {ON, OFF, OFF};
const boolean GREEN[] = {OFF, ON, OFF};
const boolean BLUE[] = {OFF, OFF, ON};
const boolean YELLOW[] = {ON, ON, OFF};
const boolean CYAN[] = {OFF, ON, ON};
const boolean MAGENTA[] = {ON, OFF, ON};
const boolean WHITE[] = {ON, ON, ON};



void setup()
{
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(blueLed, OUTPUT);
}

void loop()
{
potValue = analogRead (potPin);
if (potValue > -1 && potValue < 170) {
setColour(RED);
} else if (potValue > 170 && potValue < 341) {
setColour(YELLOW);
} else if (potValue > 341 && potValue < 512) {
setColour(GREEN);
} else if (potValue > 512 && potValue < 682) {
setColour(CYAN);
} else if (potValue > 682 && potValue < 853) {
setColour(BLUE);
} else {
setColour(MAGENTA);
}
}

void setColour(const boolean* colour)
{
digitalWrite (redLed, colour[0]);
digitalWrite (greenLed, colour[1]);
digitalWrite (blueLed, colour[2]);
}

The end result can be seen in this little video:

1 comment: