RGB LED

Discovering RGB

For this assignment i'm trying out a RGB LED. I've worked before with a Neopixel and RGB LED module, but not yet with a common cathode RGB LED.

I've looked on the internet for a tutorial which explains how to connect it and how to refer it in your Arduino code. I came across a tutorial that helped me a lot.

After everything set up i changed the code so it matched the pins on my NodeMCU. For each color pin you have to use a 220 ohm resistor.

int redPin   = D0;
int greenPin = D1;
int bluePin  = D2;

void setup() {
  
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}
void loop() {
  setColor(255, 0, 0); // Red Color
  delay(1000);
  setColor(0, 255, 0); // Green Color
  delay(1000);
  setColor(0, 0, 255); // Blue Color
  delay(1000);
  setColor(255, 255, 255); // White Color
  delay(1000);
  setColor(170, 0, 255); // Purple Color
  delay(1000);
}
void setColor(int redValue, int greenValue, int blueValue) {
  analogWrite(redPin, redValue);
  analogWrite(greenPin, greenValue);
  analogWrite(bluePin, blueValue);
}

And the result:

RGB LED with LDR as input

Now i want to try changing the RGB color by using a LDR light sensor. I haven't worked with a LDR for a few months now so I copied the code from a previous project where i used it. I connected the LDR with a 100k ohm resistor on the breadboard.

I combined the code from LDR and RGB LED so it will change color as soon as i hold my hand above the LDR so it gets darker.

int sensorPin = A0; //LDR
int redPin= D0; 
int greenPin = D1;
int bluePin = D2;
int sensorValue = 0; // variable to store the value coming from the sensor

void setup() {
Serial.begin(9600); //sets serial port for communication
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}
void loop() {
sensorValue = analogRead(sensorPin); // read the value from the sensor
Serial.println(sensorValue); //prints the values coming from the sensor on the screen


delay(100);

if (sensorValue < 1000) {
  setColor(170, 0, 255); //purple
  }

  else {
    setColor(0, 255, 0); //green
    }

}

void setColor(int redValue, int greenValue, int blueValue) {
  analogWrite(redPin, redValue);
  analogWrite(greenPin, greenValue);
  analogWrite(bluePin, blueValue);
}

Last updated