const int redPin = PA1;
const int greenPin = PA2;
const int bluePin = PA13;
int r = 0, g = 0, b = 0; // Store RGB values
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(115200);
Serial.println("RGB Controller Ready. Send commands like 'R255', 'G100', 'B000'.");
}
void loop() {
// Check if a command is waiting. We look for 4 bytes: Letter, 3 digits.
if (Serial.available() >= 4) {
char color = Serial.read(); // Read the first character (R, G, or B)
// Read the next 3 characters and convert them from text to an integer
String valueStr = "";
for (int i = 0; i < 3; i++) {
valueStr += (char)Serial.read();
}
int value = valueStr.toInt(); // Convert string "255" to integer 255
// Assign the value to the correct color variable
switch (color) {
case 'R': r = value; break;
case 'G': g = value; break;
case 'B': b = value; break;
default: Serial.println("Error: First char must be R, G, or B."); return;
}
// Print what we received and update the LED
Serial.print("Set ");
Serial.print(color);
Serial.print(" to ");
Serial.println(value);
analogWrite(redPin, r); // Control LED brightness (PWM)
analogWrite(greenPin, g);
analogWrite(bluePin, b);
}
}
Loading
st-nucleo-c031c6
st-nucleo-c031c6