Description
For this week's lab we had to choose a good diffuser for our RGB LEDs. My winner was a Tide wash bag that gave an almost omogenous effect of color. I uploaded a video with the result on youtube (http://www.youtube.com/watch?v=GhfzUGG6OrQ).
We then had to change the code to control the RGB values with multiple key presses. In my code, I asked the user to give me a string of "r", "g" and "b" and changed the brightness of each led accordingly. 0 "r"s turned off the red led whereas 10 "r"s turned it fully on (r value 255).
Components
1 Arduino Uno
1 Breadboard
3 leds
1 220 Ohm resistor
cables
Code
/*
* Serial RGB counting
* ---------------
* Serial commands control the brightness of R,G,B LEDs
*
* Command structure is "string", where "string" is a text input from the user
* Code counts the number of "r","g" or "b" in the string. "colorVal" is a number 0 to 255.
* E.g. "rrrbbbbb" turns the red LED to 30%, turns the green LED off and the blue LED on to 50%.
*
* Created 24 September 2013
*/
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 colorValr,colorValg,colorValb,r,g,b,n;
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 mid brightness
analogWrite(greenPin, 0); // set them all to mid brightness
analogWrite(bluePin, 0); // set them all to mid brightness
Serial.println("Change the brightness (from 0-10) of the led typing r,g,b multiple times.");
}
void loop () {
//Turn off the leds.
r=0; g=0; b=0;
// clear the string
memset(serInString, 0, 100);
//read the serial port and create a string out of what you read
readSerialString(serInString);
n=0;
colorCode = serInString[0];
while( colorCode != '\0' ) {
//as long as there is a string look for rgb characters
if (colorCode == 'r')
r++;
else if (colorCode == 'g')
g++;
else if (colorCode == 'b')
b++;
serInString[n] = 0; // indicates we've used this string
n++;
colorCode = serInString[n];
}
//output the value with brightness from 0-10
colorValr = floor(r*2.55);
colorValg = floor(g*2.55);
colorValb = floor(b*2.55);
analogWrite(redPin, colorValr);
analogWrite(greenPin, colorValg);
analogWrite(bluePin, colorValb);
while (!Serial.available()) {
delay(500); // 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++;
}
}
- Login to post comments