Serial Controlled LEDs
Set up the Arduino to control three LEDs via serial input. Entering (b)lue, (g)reen, or (y)ellow cycles through color values.
Components Used
Arduino Diecmila Board
220 Ohm Resistor (3)
LED (3)
Breadboard (1)
Wires (4)
Jumpers (3)
Ping-pong (disco) ball
Arduino Code
/*
* Serial RGB LED
* ---------------
* Serial commands control the brightness of R,G,B LEDs
*/
char serInString[100]; // array that will hold the different bytes of the string. 100=100characters;
// -> you must state how long the array will be else it won't work properly
char colorCode;
int colorVal;
int yellowPin = 9; // Yellow LED, connected to digital pin 9
int greenPin = 10; // Green LED, connected to digital pin 10
int bluePin = 11; // Blue LED, connected to digital pin 11
float yellowValue = 102;
float blueValue = 102;
float greenValue = 102;
float increment = 5;
boolean disco = false;
void setup() {
pinMode(yellowPin, OUTPUT); // sets the pins as output
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(9600);
// set initial brightness values
analogWrite(yellowPin, yellowValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
Serial.println("press (b)lue, (g)reen, or (y)ellow to cycle that color :");
}
void loop () {
//read the serial port and create a string out of what you read
readSerialString(serInString);
colorCode = serInString[0];
if( colorCode == 'r' || colorCode == 'g' || colorCode == 'b' ) {
disco = false;
colorVal = atoi(serInString+1);
serInString[0] = 0; // indicates we've used this string
incrementAndUpdateColor(colorCode);
}
else if (colorCode == 'd'){
disco = true;
}
if(disco)discoLoop();
delay(100); // wait a bit, for serial data
}
//read a string from the serial and store it in an array
//you must supply the array variable
void readSerialString (char *strArray) {
int i = 0;
if(!Serial.available()) {
return;
}
while (Serial.available()) {
strArray[i] = Serial.read();
i++;
}
}
void incrementAndUpdateColor(char color){
Serial.print(colorCode);
Serial.print(" ");
if(color == 'y') {
yellowValue < 255 ? yellowValue += increment : yellowValue = 0;
analogWrite(yellowPin, yellowValue);
Serial.print((int)yellowValue);
}
else if(color == 'g'){
greenValue < 255 ? greenValue += increment : greenValue = 0;
analogWrite(greenPin, greenValue);
Serial.print((int)greenValue);
}
else if(color == 'b'){
blueValue < 255 ? blueValue += increment : blueValue = 0;
analogWrite(bluePin, blueValue);
Serial.print((int)blueValue);
}
Serial.println();
}
void discoLoop(){
analogWrite((int)random(9, 11), (int)random(0, 255));
delay((int)random(10, 200));
}