LAB2
Description
Use Keyboard to control LED color combination.
Components Used
- R,G,B LEDs
- Resistors 220
- Wires
- Diffuser
Arduino Code
/*
* Serial RGB LED - TUI Homework
* ---------------
* Serial commands control the brightness of R,G,B LEDs
*
* Command structure is multiple typing or 'r' 'g' 'b' keys
*/
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 redPin = 9; // Red 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
void setup() {
pinMode(redPin, OUTPUT); // sets the pins as output
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
Serial.begin(9600);
analogWrite(redPin, 0); // set them all to no brightness
analogWrite(greenPin, 0); // set them all to no brightness
analogWrite(bluePin, 0); // set them all to no brightness
Serial.println("play light with 'r','g','b' keys :");
}
void loop () {
// clear the string
memset(serInString, 0, 100);
//read the serial port and create a string out of what you read
readSerialString(serInString);
colorCode = serInString[0];
serInString[0] = 0; // indicates we've used this string
if(colorCode == 'r')
analogWrite(redPin, 51);
else if(colorCode == 'rr')
analogWrite(redPin, 102);
else if(colorCode == 'rrr')
analogWrite(redPin, 153);
else if(colorCode == 'rrrr')
analogWrite(redPin, 204);
else if(colorCode == 'rrrrr')
analogWrite(redPin, 255);
else if(colorCode == 'g')
analogWrite(greenPin, 51);
else if(colorCode == 'gg')
analogWrite(greenPin, 102);
else if(colorCode == 'ggg')
analogWrite(greenPin, 153);
else if(colorCode == 'gggg')
analogWrite(greenPin, 204);
else if(colorCode == 'ggggg')
analogWrite(greenPin, 255);
else if(colorCode == 'b')
analogWrite(bluePin, 51);
else if(colorCode == 'bb')
analogWrite(bluePin, 102);
else if(colorCode == 'bbb')
analogWrite(bluePin, 153);
else if(colorCode == 'bbbb')
analogWrite(bluePin, 204);
else if(colorCode == 'bbbbb')
analogWrite(bluePin, 255);
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++;
}
}