/*
* Code for cross-fading one half of steak tray using PWM
* The program cross-fades slowly from right to left and back again.
* The debugging code assumes Arduino 0004, as it uses the new Serial.begin()-style functions
* Original three-LED crossfade by Clay Shirky (clay.shirky at nyu dot edu) (example from Arduino site)
* modified  by R. Stern (stern at parsons dot edu)
*/

// Output
int rightPin   = 9;
int leftPin = 10;

// Program variables
int rightVal   = 255; // Variables to store the values to send to the pins
int leftVal = 1; 

int i = 0;     // Loop counter    
int wait = 50; // 50ms (.05 second) delay; shorten for faster fades
int DEBUG = 0; // DEBUG counter; if set to 1, will write values back via serial

void setup()
{
  pinMode(rightPin,   OUTPUT);   // sets the pins as output
  pinMode(leftPin, OUTPUT);   
//  pinMode(bluePin,  OUTPUT); 
  if (DEBUG) {           // If we want to see the pin values for debuggingÉ
    Serial.begin(9600);  // ...set up the serial ouput on 0004 style
  }
}

// Main program
void loop()
{
  i += 1;      // Increment counter
  if (i < 255) // First phase of fades
  {
    rightVal   -= 1; // right down
    leftVal += 1; // left up
  }
  else if (i < 509) // Second phase of fades
  {
    rightVal = 1; // right low
    leftVal -= 1; // left down
  } 
  else if (i < 763) // Third phase of fades
  {
    rightVal  += 1; // right up
    leftVal = 1; // left low
  }
  else // Re-set the counter, and start the fades again
  {
    i = 1;
  }  

  analogWrite(rightPin,   rightVal);   // Write current values to LED pins
  analogWrite(leftPin, leftVal); 

  if (DEBUG) { // If we want to read the output
    DEBUG += 1;     // Increment the DEBUG counter
    if (DEBUG > 10) // Print every 10 loops
    {
      DEBUG = 1;     // Reset the counter

      Serial.print(i);       // Serial commands in 0004 style
      Serial.print("\t");    // Print a tab
      Serial.print("R:");    // Indicate that output is right value
      Serial.print(rightVal);  // Print right value
      Serial.print("\t");    // Print a tab
      Serial.print("L:");    // Repeat for left
      Serial.println(leftVal); // println, to end with a carriage return
    }
  }
  delay(wait); // Pause for 'wait' milliseconds before resuming the loop
}