A2: Digital I/O

Posted by dperry

dperry's picture

Description

Design a diffuser for your RGB LEDs

Change the code so that you can control the RGB values through key presses.

Components

  • (LED):  red, green, and blue
  • Resistors (220 ohms) x 3
  • Arduino board
  • styrofoam peanut

Code

// This code will raise the red, green, blue values with the user's input from the keyboard
 * Based on Code 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(7000); // begins after seven seconds
  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 either r, b or g:");
}
 
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 50, and if you reach 255 go back to 0
        redValue = (redValue + 50) % 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 + 40) % 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 + 40) % 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;

A2_I:O.jpg
0
Your rating: None