Arduino: RGB Gradient

In this challenge we will use the Arduino board to control a RGB LED to create a gradient light effect where the LED will fade from red to purple, to blue, to purple and back to red.

gradient-red-blue-red

You do not need to have access to an Arduino board. Instead you can use the online Arduino simulator from Tinkercad to recreate the electronic circuit and add the code provided below.

Open Tinkercad in new window

RGB Colour Codes


Did you know that every colour on the screen can be represented using an RGB code (Red, Green, Blue) code. This code consists of three numbers between 0 and 255, indicating how much red, green and blue are used to recreate the colour.

For instance the RGB code for:

  • Red is (255,0,0)
  • Green is (0,255,0)
  • Blue is (0,0,255)
  • Yellow is (255,255,0)
  • Orange is (255,165,0)

Check the following RGB Color picker to see how RGB codes work:

Electric Circuit


An RGB LED is a 3-in-1 LED. It consists of a RED LED, a Green LED and a Blue LED all within the same component. It has 3 cathodes (+ pins) that can take different amperages. It has 1 common anode (- pin).
RGB-LED
This is how we will connect our RGB LED to our Arduino board.
arduino-RGB-gradient

The purpose of the resistors is to limit the amperage in the circuit and hence protect the LED from receiving a too strong current (which could damage the LED). The resistors we use here are 100 ohms (Brown Black Brown rings).

C/C++ Code

// Arduino - RGB Gradient - www.101computing.net/arduino-rgb-gradient
int redOut = 13;
int greenOut = 11;
int blueOut = 12;

void setup() {
  pinMode(redOut, OUTPUT);
  pinMode(greenOut, OUTPUT);
  pinMode(blueOut, OUTPUT);
}

void setRGB(int red, int green, int blue)
 {
    analogWrite(redOut, red);
  	analogWrite(greenOut, green);
  	analogWrite(blueOut, blue);
}

void loop() {
  int red = 255;
  int green = 0;
  int blue = 0;
  for (int i = 0; i <= 255; i++) {
    blue = i;
	setRGB(red,green,blue);
    delay(20);
  } 
  for (int i = 0; i <= 255; i++) {
    blue = 255 - i;
	setRGB(red,green,blue);
    delay(20);
  } 
  
}

Your Challenge


Tweak this code to create other gradient animations:
Gradient 1: Cyan, Magenta, Cyan
gradient-cyan-magenta-cyan
Gradient 2: Cyan, Yellow, Cyan
gradient-cyan-yellow-cyan
Gradient 3: Green, Yellow, Magenta, Cyan, Green
gradient-green-yellow-magenta-cyan-green

Did you like this challenge?

Click on a star to rate it!

Average rating 3.4 / 5. Vote count: 49

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!