/******************************************************************************
 * TangibleTec, LLC
 * Ruben Kackstaetter
 *
 * License:
 * Attribution Non-commercial Share Alike 2.5 (by-nc-sa)
 * http://creativecommons.org/licenses/by-nc-sa/2.5/legalcode
 *  
 * Purpose:
 * Arduino Sketch to control PWM from a comma separated list via serial command
 * 
 * Wiring:
 * Any PWM pins 3, 5, 6, 9, 10, 11
 *****************************************************************************/

// 1 - enables debug
#define DEBUG 0
 
// Change to the number of PWM pins you wish to use
const int NUM_PWM_PINS = 3;
const int PIN_LIST[] = {3, 5, 6, 9, 10, 11};

int pos_list[] = {255, 255, 255, 255, 255, 255};
int target_pos[] = {0, 0, 0, 0, 0, 0};

void setup()
{
  Serial.begin(115200);  // start serial port
  delay(100);
  
  // Setup pins from PIN_LIST as outputs, and write start position from pos_list.
  for (int i = 0; i < NUM_PWM_PINS; i++) {
    pinMode(PIN_LIST[i],OUTPUT);
    analogWrite(PIN_LIST[i], pos_list[i]);
  }
}

void loop()
{
  while (Serial.available() > 0) {
    // look for the next valid integer in the incoming serial stream
      for (int i = 0; i < NUM_PWM_PINS; i++) {
        pos_list[i] = Serial.parseInt();
      }
    if (Serial.read() == '\n')
    { 
      // 
      for (int i = 0; i < NUM_PWM_PINS; i++) {
        analogWrite(PIN_LIST[i], pos_list[i]);
      }
    }

// Debug messages
// NOTE: Be sure your connected serial device is emptying it's buffer,
//       otherwise, it will fill up fast and cause your device to hang.
#if DEBUG
    Serial.print(pos_list[0]);
    Serial.print(",");
    Serial.print(pos_list[1]);
    Serial.print(",");
    Serial.println(pos_list[2]);
#endif

  }
}