/*
 * Bluetooth Test
 *
 * This program tests connectivity between an Arduino Uno connected to
 * a bluetooth modem, and a bluetooth enabled computer (or in my case cell phone)
 */
 
 //
 // Global Variables
 //
 char cVal = 'L';

// Brighten And Fade an LED
void FadeAndBrighten (int iPin, int iIncr) {
  
  // start with led off and go to max brightness
   for (int i=0; i <= 255; i+=iIncr) {

     // set the brightness of the pin:
    analogWrite(iPin, i);    

    // wait for 30 milliseconds to see the effect    
    delay(30);
   }
   
   // Now dim the led
   for (int i = 255; i>=0; i-= iIncr) {
     // set the brightness of the pin:
    analogWrite(iPin, i);    

    // wait for 30 milliseconds to see the effect    
    delay(30);
   }
}

// Set LED on, wait, Set LED off, wait
void LedOnAndOff (int iPin) {
  digitalWrite(iPin, HIGH);  
  delay(1000);               
  digitalWrite(iPin, LOW);    
  delay(1000);                
}

// Read data from the serial port (modem).  When an 'h' is read toggle the green
// LED high.  Any other data sets the green LED low.  The yellow led is pulsed 
// any time data is read from the serial port.
void SerialTest (int iPin, int iSig) {
  String str = "";
  
  if( Serial.available() )     
  {
    // data is available to read
    digitalWrite(iSig, HIGH);
    
    while (Serial.available() ) {
      cVal = Serial.read();       // read it and store it in 'val';
      str += cVal;
    }
    Serial.print("The result is: ");
    Serial.println(str);
    
    if( str != "" && (str[0] == 'H' || str[0] == 'h') ) {
      digitalWrite(iPin, HIGH);
    } else {
      digitalWrite(iPin, LOW);
    }
  } else {
    digitalWrite(iSig, LOW);
  }
  
  // wait 100ms for next reading
  delay(100);                   
}

// Initialization function called once when sketch is started
void setup()  { 
  // declare output pins:
  pinMode(9, OUTPUT);
  pinMode(7, OUTPUT);

  // setup serial communication
  Serial.begin(115200);
  //Serial.flush();
  
  // Test the LEDs on the board
  LedOnAndOff (9);
  LedOnAndOff (7);
} 

// Loop forever
void loop()  { 
  SerialTest (9,7);
}