Tuesday, June 5, 2012

Rainbow Arduino: Part 2

So after making the LED light up in rainbow colors, I decided to make it more interactive. I combined my code with this one from the Arduino site. 


I'm using this photoresistor to adjust the colors of the RGB LED with the same wiring from the last code. 




I had to sketch a little graph in my planner to figure this out since I am not a programming genius.

as you can see, finals ended on the 15th

If you are interested in the code: 

// These constants won't change:

const int sensorPin = A0;    // pin that the sensor is attached to
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
const int power = 9;

// variables:
int sensorValue = 0;         // the sensor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value
int red = 0;
int green = 0;
int blue = 0;

void setup() {

// set the pins as output:
  pinMode(redPin, OUTPUT); 
  pinMode(greenPin, OUTPUT); 
  pinMode(bluePin, OUTPUT); 
  pinMode(power,OUTPUT);
  
 // turn on LED to signal the start of the calibration period:
pinMode(13,OUTPUT);
digitalWrite(13,HIGH);

// calibrate during the first five seconds 
  while (millis() < 5000) {
    sensorValue = analogRead(sensorPin);
    Serial.println(sensorValue);

    // record the maximum sensor value
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
      Serial.println(sensorMax);  }

    // record the minimum sensor value
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
      Serial.println(sensorMin); }
 }
  digitalWrite(13,LOW);
  // signal the end of the calibration period 
}

void loop() {
  // read the sensor:
  sensorValue = analogRead(sensorPin);
  // apply the calibration to the sensor reading
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
  // in case the sensor value is outside the range seen during calibration
  sensorValue = constrain(sensorValue, 0, 255);
  // fade the LED using the calibrated value:
if(sensorValue<127) {
  red= (-2*sensorValue)+255;  // decreasing the red
  green = 2*sensorValue;   // increasing the green
  analogWrite(redPin, red);
  analogWrite(greenPin, green); }
if(sensorValue>127 {
  green= (-2*sensorValue)+510;  // decreasing the green
  blue = 2*(sensorValue) - 255;   // increasing the blue
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue); }
}



No comments:

Post a Comment