STANNUM
Open the simulator

Tutorials / Output

RGB LED

Three LEDs in one package, one GPIO each — red, green and blue mix into eight colors.

Parts in the example:
  • Joystick
  • RGB LED
The RGB LED block as it appears on the canvas.

What it is

An RGB LED is three LEDs sharing one dome and, in the common-cathode kind modeled here, one ground leg. Drive each anode from its own GPIO and the eye adds the three lights: red and green make yellow, all three make white.

In the simulator

The block is a single dome whose color is the mix of the three channels. Each channel is either on or off, so the palette is the eight combinations of R, G and B. In the example, a joystick chooses: X to the right lights red, Y up lights blue, the stick's button lights green.

Pins

PinWhat it is
Rred anode — to a GPIO
Ggreen anode — to a GPIO
Bblue anode — to a GPIO
Kcommon cathode — to a GND symbol

Wiring

The circuit below is the example RGB LED colors with a joystick from the lab — open it with Project → Open example… and it comes ready to run.

The wired circuit, as the lab draws it.
RGB LED pinGoes to
RD25 on the board (GPIO 25)
GD26 on the board (GPIO 26)
BD27 on the board (GPIO 27)
Ka GND symbol

Code

sketch.cpp
#include <Arduino.h>

const int VX = 34;   // joystick X axis (ADC)
const int VY = 35;   // Y axis (ADC)
const int SW = 33;   // joystick button
const int R = 25, G = 26, B = 27;

void setup() {
  Serial.begin(115200);
  pinMode(R, OUTPUT); pinMode(G, OUTPUT); pinMode(B, OUTPUT);
  pinMode(SW, INPUT_PULLUP);
}

void loop() {
  int x = analogRead(VX);          // 0..4095, at rest ~2048
  int y = analogRead(VY);
  bool apertado = digitalRead(SW) == LOW;

  digitalWrite(R, x > 2800 ? HIGH : LOW);
  digitalWrite(B, y > 2800 ? HIGH : LOW);
  digitalWrite(G, apertado ? HIGH : LOW);

  Serial.printf("x=%d y=%d button=%d\n", x, y, apertado);
  delay(100);
}

digitalWrite on three pins is all it takes. The joystick's two axes are read with analogRead and compared with a threshold (2800 of 4095) to decide whether a channel goes on; the stick's button is read as a digital input with the pull-up on.

Run it

Press Build and run. The first build of a project takes a while; after that, only what changed is rebuilt.

The simulation running: the canvas reacts and the serial monitor shows what the code prints.

Drag the stick on the joystick block and watch the dome change color; release it and it springs back to the center (every channel off). Press the stick's SW button for green.

How the simulation models it

Try this

  1. Cycle through the eight colors with a for loop over the three bits, one color per second.
  2. Make the color depend on the potentiometer of another example: below 1/3 red, in the middle green, above 2/3 blue.

See also