// by justin downs

// sends serial data of an analog messege displays it in an led



#define potPin = 0; //analog in pin

#define outputPin = 10; //a out led

#define ledPin = 13; // led

int valuein =0;

int valueout =0;

char inByte = 0;

long prevmilles= 500;

long prevmilles2= 500;

long prevmilles3= 500;


void setup () {

  // set pins to input and output appropriately

  pinMode(ledPin, OUTPUT);

  pinMode(outputPin, OUTPUT);


  // start up the serial connection with 9600-8-n-1-true (non-inverted):

  Serial.begin(9600);


  // blink the status LED

  blinkLED(ledPin, 3);


  // for some reason it seems to help to send an arbitrary character first

  //then pause for the guard time before requesting command mode

  Serial.print("X");

  delay(1100);

  // put the XBee in command mode

  Serial.print("+++");

  delay(1100);

  // wait for a response from the XBee for 2000 ms, or start

  // over with setup if no valid response comes

  if (returnedOK() == 'T') {

    // if an OK was received then continue 

  }

  else {

    setup(); // otherwise go back and try setup again

  }

  // could do in one print

  Serial.print("ATID2222,");

  Serial.print("MY2,");

  Serial.print("DH0,");

  Serial.print("DL1,");

  Serial.println("CN");


  if (returnedOK() == 'T') {

    // if an OK was received then continue 

  }

  else {

    setup(); // otherwise go back and try setup again

  }


}





void loop () {

  if (millis() - prevmilles >=100){ 

    valuein = (analogRead(potPin)/4);

    Serial.print('a');

    Serial.print(valuein);

    Serial.print('b');

    prevmilles = millis();

  }


  if (millis() - prevmilles3 >=100){ 

    if (Serial.available() > 1) {

      valueout=SerialLook();

      analogWrite(10, valueout);

    }

    prevmilles3 = millis();

  }

}




//FUNCS//


void blinkLED(int targetPin, int numBlinks) {

  // this function blinks the status LED light as many times as requested

  for (int i=0; i<numBlinks; i++) {

    digitalWrite(outputPin, HIGH); // sets the LED on

    delay(250); // waits for a second

    digitalWrite(outputPin, LOW); // sets the LED off

    delay(250);

  }

}

char returnedOK () {

  // this function checks the response on the serial port to see if it was an "OK" or not

  char incomingChar[3];

  char okString[] = "OK";

  char result = 'n';

  int startTime = millis();

  while (millis() - startTime < 2000 && result == 'n') { // use a timeout of 10 seconds

    if (Serial.available() > 1) {

      // read three incoming bytes which should be "O", "K", and a linefeed:

      for (int i=0; i<3; i++) {

        incomingChar[i] = Serial.read();

      }

      if ( strstr(incomingChar, okString) != NULL ) { // check to see if the respose is "OK"

        // if (incomingChar[0] == 'O' && incomingChar[1] == 'K') { // check to see if the first two characters are "OK"

        result = 'T'; // return T if "OK" was the response

      } 

      else {

        result = 'F'; // otherwise return F

      }

    }

  }

  return result;

}








long SerialLook() {

  char ASCIIString [100]; // in string

  char inByte='c'; 

  long number = 0; // return number

  int stringPos = 0; // keeps track of places in number

  if ('a' == Serial.read()){ // for id parsing of serial

    while(inByte !='b'){

      inByte = Serial.read();


      // save ASCII numeric characters in string:

      if ((inByte >= '0') && (inByte <= '9')){

        // Serial.println( inByte);

        ASCIIString [stringPos] = inByte;

        stringPos++;

        // Serial.println( stringPos);

      }

    }

  }

  Serial.flush(); // flush junk

  number = SerialToInt( ASCIIString,stringPos ); /// convert captured string to an int


  stringPos = 0; //reset count num 

  return number;

}


/*****************

 * the important parts of the function conversions 

 * are to have a inverting for loop go 

 * from last in array to first and call the plusBaseTen()function

 * each time.

 *******************/


// hits up the number by base ten powered

long timesBaseTen(int _move){ // the

  long place = 1; //base 10

  int n = 0;

  if( _move < 1){ 

    return 1;

  }//ones place no change

  else{

    for( n= 0; n<_move; n++){ 

      place = place*10;

    }

  }

  return place;

} 




// converts a ten digit ASCII to int

long SerialToInt(char *_input, int _arrayLength){

  long number=0;

  long total=0;

  int arrayLook=0;

  int i = 0;

  char s[]={

    "h"  }; // work around 

  int arrayLength =_arrayLength-1; // need one less than actual length 0 is 1

  // call invert string for proper string power order

  for(i =arrayLength; i >= 0;i--){ 

    // Serial.println(i);

    // Serial.println(_input[i]); 

    // picks out ASCII numbers for error check

    if ((_input[i] >= '0') && (_input[i]<= '9')){ 

      s[0] = _input[i];// work around to get string arg

      number = atoi(s);// ASCII to converts number

      number = (number * (timesBaseTen(arrayLook))); // puts number in its place

      arrayLook++;

      total = number+total;

    }

  }

  return total; 

}