Skip to content

Instantly share code, notes, and snippets.

@idkrn123
Created November 20, 2023 22:20
Show Gist options
  • Save idkrn123/237417b4e876f7e245cff4293e3c87d4 to your computer and use it in GitHub Desktop.
Save idkrn123/237417b4e876f7e245cff4293e3c87d4 to your computer and use it in GitHub Desktop.
serial_colors.ino - experimental arduino sketch to read 3 rgb bytes input and write to 3 pins for an rgb led
const int redPin = 9;
const int greenPin = 10;
const int bluePin = 11;
bool firstInputReceived = false;
void setup() {
Serial.begin(9600);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// Blink red until the first valid input is received
if (!firstInputReceived) {
blinkRed();
}
// Check if at least 3 bytes have been received
if (Serial.available() >= 3) {
// Read the RGB values
int redValue = Serial.read();
int greenValue = Serial.read();
int blueValue = Serial.read();
// Check if the values are within the valid range (0-255)
if (isValidValue(redValue) && isValidValue(greenValue) && isValidValue(blueValue)) {
// Set the RGB LED color
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
firstInputReceived = true; // Mark the first input as received
} else {
// Blink red to indicate an error
blinkRed();
}
}
}
// Function to blink the LED red
void blinkRed() {
setColor(255, 0, 0); // Set LED to red
delay(500); // Wait for 500ms
setColor(0, 0, 0); // Turn off LED
delay(500); // Wait for 500ms
}
// Function to set the color of the RGB LED
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}
// Function to check if the value is within the valid range
bool isValidValue(int value) {
return value >= 0 && value <= 255;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment