Arduino Mega and Bluetooth Mate not acting as a data pipe.

Hi,

I'm working on a QT application that will communicate with an Arduino over Bluetooth. I haven't worked much with Arduinos before and have run into some problems. I'm using an Arduino Mega and a Bluetooth Mate Gold from SparkFun. My code is also based off their tutorial found here:

https://learn.sparkfun.com/tutorials/using-the-bluesmirf/example-code-using-command-mode

I took that to configure the module, and I added code to detect 1s and 0s to turn an LED on and off.

My exact code is shown below:

#include <SoftwareSerial.h>

//Variables.
char val;
int ledPin = 13;

//Pin declarations.
int bluetoothTXPin = 2;
int bluetoothRXPin = 3;

//Serial connection declaration.
SoftwareSerial bluetooth(bluetoothTXPin, bluetoothRXPin);

void setup()
{
  //Begin serial stream.
  Serial.begin(9600);
  
  //Initialize Bluetooth module.
  bluetooth.begin(115200);
  
  //Sets module to command mode.
  bluetooth.print("$");
  bluetooth.print("$");
  bluetooth.print("$");
  
  //Delay to wait for module to respond with a command.
  delay(100);
  
  //Changes baud rate to 9600bps.
  bluetooth.println("U,9600,N");
  
  //Bluetooth serial connection is started at 9600bps
  bluetooth.begin(9600);
  
  pinMode(13, OUTPUT);
  digitalWrite(ledPin, LOW);
}

void loop()
{
  //Bluetooth logic.
  if(Serial.available())
  {   
    Serial.print((char)bluetooth.read());
    val = Serial.read();
    
    if(val == '0')
    {
      digitalWrite(ledPin, LOW);
      delay(1000);
      Serial.println("13 off");
    }
    if(val == '1')
    {
      digitalWrite(ledPin,LOW);
      digitalWrite(ledPin, HIGH);
      delay(1000);
      Serial.println("13 on");  
    }  
  }
}

Using Tera Term, I can connect to the Bluetooth module and enter command mode, but according to the data sheet I should be able to use the Bluetooth connection as a stream when not in command mode. When I try to send a 1 or 0 to manipulate the LED, nothing happens. I'm not sure what the problem is, but I wouldn't be surprised if it's something obvious.

Any suggestions to fix this problem would be appreciated!

Alright, I've changed my code around, but still have a problem. I can successfully receive text from the module when bluetooth.println() is used, but I cannot get the module to detect incoming characters. I have a line of code that waits for incoming data before progressing through the loop as shown below:

while (bluetooth.available() <= 0);

When I type a 1 or 0 in to Tera Term, I do not get a response. The loop never passes this line. Any ideas?