Fading Light
/*
* Serial RGB LED
* ---------------
* Serial commands control the brightness of R,G,B LEDs
*
* Command structure is "<colorCode><colorVal>", where "colorCode" is
* one of "r","g",or "b" and "colorVal" is a number 0 to 255.
* E.g. "r0" turns the red LED off.
* "g127" turns the green LED to half brightness
* "b64" turns the blue LED to 1/4 brightness
*
* Created 18 October 2006
* copyleft 2006 Tod E. Kurt <tod@todbot.com
* http://todbot.com/
*/
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 redPin = 10; // Red LED, connected to digital pin 9
int greenPin = 9; // Green LED, connected to digital pin 10
int bluePin = 11; // Blue LED, connected to digital pin 11
int redValue = 127;
int greenValue = 127;
int blueValue = 127;
int input= 0; // will later return i from read SerialString
void setup() {
pinMode(redPin, OUTPUT); // sets the pins as output
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(9600);
analogWrite(redPin, redValue); // set them all to mid brightness
analogWrite(greenPin, greenValue); // set them all to mid brightness
analogWrite(bluePin, blueValue); // set them all to mid brightness
Serial.println("enter color command as r's b's and g's :");
}
void loop () {
//clears the string
memset(serInString, 0, 100);
//read the serial port and create a string out of what you read
input = readSerialString(serInString);
//reads commands of the form 'rrr'
delay(100); // wait a bit, for serial data
colorCode = serInString[0];
for(int i=0;i < input; i++) {
//If the character is r (red)...
if (colorCode == 'r') {
//Increase the current red value by 25, and if you reach 255 go back to 0
redValue = (redValue + 25) % 255;
analogWrite(redPin, redValue);
Serial.print("setting color r to ");
Serial.println(redValue);
//If the character is g (green)...
} else if (colorCode == 'g') {
greenValue = (greenValue + 25) % 255;
analogWrite(greenPin, greenValue);
Serial.print("setting color g to ");
Serial.println(greenValue);
//If the character is b (blue)...
} else if (colorCode == 'b') {
blueValue = (blueValue + 25) % 255;
analogWrite(bluePin, blueValue);
Serial.print("setting color b to ");
Serial.println(blueValue);
}
}
}
//read a string from the serial and store it in an array
//you must supply the array variable
int readSerialString(char *strArray) {
int i = 0;
if(!Serial.available()) {
return 0;
}
while (Serial.available()) {
strArray[i] = Serial.read();
i++;
}
return i; // lets you store the string i will eventually loop through. essentially the length of array.
}