Tuesday, March 2, 2010

PWM RGB LED Part 2

This code is built of code from the previous post but works slightly different (namely it uses arrays and for loops rather than explicitly defining pins and value changes) and has a new feature: fading of each colour to both extremes and then back again:

boolean go = HIGH;
int pins [3] = {11,10,9};
int colours [3] = {0,0,0};
boolean dir [3] = {HIGH,HIGH,HIGH};

void setup() {
randomSeed(analogRead(5));
Serial.begin(9600);
}

void loop() {
if (go == HIGH){
go = !go;
for (int i = 0; i < 3; i ++){
colours[i] = random(1,255);
} //sets up initial values for cycling
}

for (int i = 0; i < 3; i ++){
if (dir[i] == HIGH){
colours[i] += 5;
if (colours[i] >= 250){ //if this value exceeds 255 then that colour will turn off resulting in a flash when it drops below 255 again
dir[i] = LOW;
}
}
else
{
colours[i] -= 5;
if (colours[i] <= 5){
dir[i] = HIGH;
}
}
analogWrite(pins[i],colours[i]);
}
delay(30);
}

EDIT

Did some playing around with the above code and now in the beginning loop when first assigning values it will also randomize the beginning direction of the colour value as well as randomizing the incrementing value.

No comments:

Post a Comment