October 7, 2011

Red Green Blue (RGB) LED

Red, green and blue are the primary colors of light: any color can be defined as proportions of these three. Each pixel of a typical computer screen is a tiny RGB LED. The pins are ordered R - [cathode, longest] - G - B. I often make mistakes here in code because my initials are LBG.




2 comments:

  1. int rPin = 11;
    int gPin = 10;
    int bPin = 9;

    void setup()
    {
    pinMode(rPin, OUTPUT);
    pinMode(gPin, OUTPUT);
    pinMode(bPin, OUTPUT);
    Serial.begin(9600);
    }

    void loop()
    {
    analogWrite(rPin, random(255));
    analogWrite(gPin, random(255));
    analogWrite(bPin, random(255));
    delay(1000);
    }

    ReplyDelete
  2. With this code, the lights get progressively dimmer. The blue goes first, then green, then red (the inverse of whichever order they appear in the loop). The first in line is much more persistent than the others. Why? Is this because of random() somehow?


    int lPin = 0;
    int firstRed, lastRed, thisRed = 0;
    int rPin = 11;
    int firstGreen, lastGreen, thisGreen = 0;
    int gPin = 10;
    int firstBlue, lastBlue, thisBlue = 0;
    int bPin = 9;

    void setup(){
    Serial.begin(9600);
    firstRed = 100;
    lastRed = firstRed;
    firstGreen = 100;
    lastGreen = firstGreen;
    firstBlue = 100;
    lastBlue = firstBlue;
    }

    void loop(){
    // Serial.println(analogRead(lPin));
    int lux = map(analogRead(lPin), 200, 900, -50, 100);

    lastRed += int(random(-10,10));
    thisRed = constrain(lastRed + lux, 0, 255);
    Serial.print("red =");
    Serial.println(thisRed);
    analogWrite(rPin, thisRed);

    lastGreen += int(random(-10,10));
    thisGreen = constrain(lastGreen + lux, 0, 255);
    Serial.print("green =");
    Serial.println(thisGreen);
    analogWrite(gPin, thisGreen);

    lastBlue += int(random(-10,10));
    thisBlue = constrain(lastBlue + lux, 0, 255);
    Serial.print("blue =");
    Serial.println(thisBlue);
    analogWrite(bPin, thisBlue);

    delay(200);
    }

    ReplyDelete