// Configuring HC-06 Via Bluetooth Demo
// By keuwlsoft: www.keuwl.com 30th Sept 2015
// cc Attribution-ShareAlike
// Used with an Android device running keuwlsofts 'Bluetooth Electronics'
// app with the 'Configure HC-06 demo' panel. Program baud rate, name and
// pin on a second HC-06 module connected to the software serial.
#include <SoftwareSerial.h> //library for software serial
//define software serial: RX on Pin 8, TX on Pin 9
SoftwareSerial softSerial(8, 9);
long baud_rates[]={1200,2400,4800,9600,19200,38400,57600,115200};
int baud_index=3;
char BluetoothData; // the data received from bluetooth serial link
boolean found_baud=false; //Flag to indicate if baud rate has been detected
void setup() {
Serial.begin(9600); //Initialise serial for communicating to android device
}
void loop() {
if (Serial.available()){
BluetoothData=Serial.read(); //Get next character from bluetooth
//Find Baud Rate
if(BluetoothData=='F') find_baud_rate();
//Set Baud Rate
if(BluetoothData>48&&BluetoothData<57){ //chars '1' to '8'
if (!found_baud) find_baud_rate();
softSerial.print("AT+BAUD"+String(BluetoothData-48));
delay(1500);
if (softSerial.available()) Serial.println("Response="+softSerial.readString());
softSerial.end();
baud_index=BluetoothData-49;
softSerial.begin(baud_rates[baud_index]); //Initialise software serial at new rate
}
//Set New Name or Custom Command
if(BluetoothData=='N'||BluetoothData=='C'){
String str=Serial.readString();
if (BluetoothData=='N')str="AT+NAME"+str;
if (!found_baud) find_baud_rate();
softSerial.print(str);
delay(1500);
if (softSerial.available()) Serial.println("Response="+softSerial.readString());
}
//Set New Pin
if(BluetoothData=='P'){
int pin=Serial.parseInt();
if (!found_baud) find_baud_rate();
softSerial.print("AT+PIN"+ String(pin));
delay(1500);
if (softSerial.available()) Serial.println("Response="+softSerial.readString());
}
}
}
//Function to loop through the baud rates until a response is obtained
void find_baud_rate(){
found_baud=false;
baud_index=-1;
while(!found_baud&&baud_index<8){
baud_index++;
softSerial.begin(baud_rates[baud_index]); //Initialise software serial
Serial.println("Testing "+String(baud_rates[baud_index])+" Baud ...");
delay(100);
softSerial.print("AT");
delay(1500);
if (softSerial.available()){
found_baud=true;
Serial.println(softSerial.readString()+" at "+String(baud_rates[baud_index])+" Baud");
}
if (!found_baud) softSerial.end();
}
if (!found_baud) softSerial.begin(9600); //If not found, try at 9600 anyway
}