const int redPin = 2; // Pin for controlling red LED
const int greenPin = 0; // Pin for controlling green LED
const int bluePin = 4; // Pin for controlling blue LED
const bool invert = false; // Set to true for common anode, false for common cathode
int color = 0; // Hue value from 0 to 255
int R, G, B; // Red, Green, Blue color components
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(redPin, OUTPUT); // Set pins as outputs
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
int brightness = 255; // Maximum brightness
hueToRGB(color, brightness); // Convert hue to RGB components
// Set RGB values to the corresponding PWM pins
analogWrite(redPin, R);
analogWrite(greenPin, G);
analogWrite(bluePin, B);
Serial.print("R: "); Serial.print(R);
Serial.print(" G: "); Serial.print(G);
Serial.print(" B: "); Serial.println(B);
color++; // Increment color hue
if (color > 255)
color = 0;
delay(10); // Delay for smooth color transitions
}
// Function to convert hue to RGB components
void hueToRGB(int hue, int brightness) {
unsigned int scaledHue = (hue * 6); // Scale hue to 0-1535
// Determine segment of color wheel
unsigned int segment = scaledHue / 256;
// Offset within the segment
unsigned int segmentOffset = scaledHue - (segment * 256);
unsigned int complement = 0;
unsigned int prev = (brightness * (255 - segmentOffset)) / 256;
unsigned int next = (brightness * segmentOffset) / 256;
// Adjust for common anode configuration
if (invert) {
brightness = 255 - brightness;
complement = 255;
prev = 255 - prev;
next = 255 - next;
}
// Set RGB values based on color segment
switch (segment) {
case 0: // Red
R = brightness;
G = next;
B = complement;
break;
case 1: // Yellow
R = prev;
G = brightness;
B = complement;
break;
case 2: // Green
R = complement;
G = brightness;
B = next;
break;
case 3: // Cyan
R = complement;
G = prev;
B = brightness;
break;
case 4: // Blue
R = next;
G = complement;
B = brightness;
break;
case 5: // Magenta
default:
R = brightness;
G = complement;
B = prev;
break;
}
}