// Define pins for RGB LEDs
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
String inputString = ""; // Stores input from serial
boolean stringComplete = false; // Flag to indicate whether the string is complete
void setup() {
Serial.begin(9600); // Set baud rate
// Set pins as outputs for RGB LEDs
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// Check for incoming serial data
serialEvent();
// If a complete command has been received
if (stringComplete) {
// Parse the command and set RGB values accordingly
parseCommand(inputString);
// Clear the string and reset flag
inputString = "";
stringComplete = false;
}
}
// Function to handle incoming serial data
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
inputString += inChar;
if (inChar == '\n') {
stringComplete = true;
}
}
}
// Function to parse command and set RGB values
void parseCommand(String command) {
// Find position of "#" characters
int firstHash = command.indexOf('#');
int secondHash = command.indexOf('#', firstHash + 1);
int thirdHash = command.indexOf('#', secondHash + 1);
// Extract RGB values from the command
int redValue = command.substring(firstHash + 1, secondHash).toInt();
int greenValue = command.substring(secondHash + 1, thirdHash).toInt();
int blueValue = command.substring(thirdHash + 1).toInt();
// Set RGB LED intensities
analogWrite(redPin, map(redValue, 0, 100, 0, 255));
analogWrite(greenPin, map(greenValue, 0, 100, 0, 255));
analogWrite(bluePin, map(blueValue, 0, 100, 0, 255));
}