RGB LEDs have four pins; 3 for each colour, and one for ground. I calculated the resistor values here based on the 5V PWM pin voltage, the forward current of each colour, and the forward voltage of each colour. That is, the resistor values for each colour are approximately equal to (5V - forward voltage of colour)/forward current. We need to include current limiting resistors because the forward current of each colour (approximately 20mA) is less than the maximum rated current of the PWM pins (40 mA), which would otherwise flow and likely burn out the LEDs in the absence of any resistance. I have included the basic schematic below.
The code below will simply switch between each colour. Note that 0 corresponds to LED off, and 255 corresponds to the maximum brightness for the PWM signal - something we will be including in the actual algorithm to control brightness with signal level and colour with each beat.
//Simple code toggles colour of LED at maximum brightness
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
int thisPin = redPin;
int other1 = greenPin;
int other2 = bluePin;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void loop() {
analogWrite(thisPin,255); //maximum brightness
analogWrite(other1,0); //turn off
analogWrite(other2,0); //turn off
//switches colour every second
switch (thisPin) {
case redPin:
thisPin = bluePin;
other1 = redPin;
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
int thisPin = redPin;
int other1 = greenPin;
int other2 = bluePin;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void loop() {
analogWrite(thisPin,255); //maximum brightness
analogWrite(other1,0); //turn off
analogWrite(other2,0); //turn off
//switches colour every second
switch (thisPin) {
case redPin:
thisPin = bluePin;
other1 = redPin;
other2 = greenPin;
break;
case bluePin:
thisPin = greenPin;
other1 = redPin;
other2 = bluePin;
break;
case greenPin:
thisPin = redPin;
other1 = greenPin;
other2 = bluePin;
}
delay(1000);
}
break;
case bluePin:
thisPin = greenPin;
other1 = redPin;
other2 = bluePin;
break;
case greenPin:
thisPin = redPin;
other1 = greenPin;
other2 = bluePin;
}
delay(1000);
}