Bluetooth connection (HC-06 v2.0) between Pro micro (ATmega32U4) and Android App

Hi all,

is there a basic code to program the micro controller ATmega32U4 (Pro Micro - 3.3V/8MHz) in order to generate and send readings through bluetooth (HC-06 Keyes BT_BOARD v2.0) to a custom android app? I cannot achieve pairing.

So far I have achieved hardware connection between the pro micro and the bluetooth board, the bluetooth with the name 'HC-06' can be detected by the android tablet, 1234 is used successfully as a password but no pairing is achieved.

Thank you in advance!

Seeing the name and entering the password sounds very much like pairing, so maybe it did. A confirmation that it didn't is the LED still flashing. There could be a problem with the power supply. Are you sure the shield you are using is kosher for 3.3v operation?

The LED is indeed still flashing. I used a code from an early stage of the same project ,done by somebody else, where the pro micro is connected to a SEED Studio Bluetooth Shield instead and to a PC Base Station as well doing practically the same job.

What I am currently doing is actually the same thing but instead of using the Bluetooth Shield I use the HC-06 Keyes BT_BOARD v2.0 to achieve miniaturization. I think the bluetooth shield is not using the exact same bluetooth chip as the HC-06, but they are very similar. Also, at this point connecting to pc base station is not my priority, I just want to connect to the Android app.

This is the code used for the previous stage of the project, can it be modified somehow?:

#define READINGCOUNT 25

//Global Variables
int _count; //index
int _delayCount=0; //counter to generate delay for sending readings every X seconds
int _state; //state machine - current state
String _readings[READINGCOUNT] = {"43","63","44","47","50","46","44","60","52","47","51","50","49","63","57","52","57","51","47","44","43","42","42","42","42"};
char _btRxData; //Most recent received byte from BT Shield
String _btRxBuff=""; //Local buffer for received data
char _pcRxData; //Most recent received byte from PC (over serial)

void setup()
{
//Initialise Serial Port to PC
Serial.begin(9600);

//Initialise BT Shield
BluetoothInit();
Serial.println("Bluetooth Hardware Initiated");

Serial.flush();
_count=0;
}

void loop()
{
//If new byte of data to receive from BT Shield
if(Serial1.available())
{
_btRxData = Serial1.read(); //Read it
_btRxBuff += _btRxData; //Add it to buffer
Serial.print(_btRxData); //Debug: Send to PC Console
}

//If new byte of data to receive from PC
if(Serial.available())
{
_pcRxData = Serial.read(); //Read it
Serial1.print(_pcRxData); //Relay to BT Shield
}

//Check for disconnection
if(_btRxBuff.indexOf("+BTSTATE:1") != -1) //BT STATE 1 indicates a disconnection
{
Serial.println("Debug: Disconnection Detected");

Serial1.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
delay(2000); // This delay is required.
Serial1.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
delay(2000); // This delay is required.

Serial.println("Debug: Earpiece Is Inquiring Again");
_btRxBuff=""; //Clear buffer
_state=0;
}

//Detect disconnect when remote device drops off (disconnection not properly indicated by remote device)
if(_btRxBuff.indexOf("CONNECT:FAIL") != -1)
{
Serial.println("Debug: Error Occurred");

Serial1.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
Serial1.print("\r\n+INQ=0\r\n"); //make the slave bluetooth inquirable
delay(2000); // This delay is required.
Serial1.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
delay(2000); // This delay is required.

Serial.println("Debug: Earpiece Is Inquiring Again");
_btRxBuff="";
_state=0;
}

//Main FSM logic
switch(_state)
{
case 0:
//Idle state (waiting for connection)

if(_btRxBuff.indexOf("+BTSTATE:4") != -1) //If successful connection detected?
{
//Connection has been established - clear local buffer
Serial.println("Debug: Connection Established");
_count=0;
_delayCount=0;
_btRxBuff="";
_state=1;
}
break;

case 1:
//State which starts sending readings

//Send reading every X * 1ms (current delay is 2 seconds)
//This method of delay avoids long "delay(2000)" at bottom, which would cause device to receive data 1 byte per second! (that wouldn't be good!)
if(_delayCount == 2000)
{
if(_count < READINGCOUNT) //Send the next reading in the readings array
{
Serial.println(_readings[_count]);
Serial1.print(_readings[_count]);
_count++;

}
else _count=0; //If reached end, reset

_delayCount=0; //Reset delay counter
}
else _delayCount++;

break;

default:
break;
}

//Common delay for each cycle (used in order to send data every X seconds)
delay(1);
}

void BluetoothInit()
{
Serial1.begin(38400);
Serial1.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
Serial1.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
Serial1.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
Serial1.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
delay(2000); // This delay is required.
Serial1.print("\r\n+LOSSRECONN=0\r\n");
delay(2000);
Serial1.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable
delay(2000); // This delay is required.
Serial1.flush();
}

Thank you

OK, the first thing you need to do is read the first post in the section and see how to enter code using the hash icon.

You didn't answer about the power supply but I'm not sure that matters - for the moment - as the code appears to be junk from beginning to end.

Some of this may be justified by intent outside the code shown or, less likely, something to do with the shield, but I doubt both, as one HC-06 is very much like another and, even if there is a difference between the ones you have, I bet it is immaterial.

One of the main problems is that you are incorporating Bluetooth programming in the arduino programme although the only things I can really recognise are the change of baud rate and the establishment of slave mode. Don't bother telling me why or how you do this with an HC-06. If there is an answer it will be lost on me, but I think it is a very clear indication of what is going on.

I guess the immediate objective is to prove that Bluetooth will talk to Arduino. I have never heard of a HC-06 Keyes BT_BOARD v2.0 and Google apparently hasn't heard of it either but you do say it is an HC-06 and maybe it is made specifically for the Pro Micro, so , if you are sure it will work on 3.3v, the link below has all you should need to establish communication between Arduino and Android via Bluetooth..

So maybe it will help.

http://homepages.ihug.com.au/~npyner/Arduino/GUIDE_2BT.pdf
http://homepages.ihug.com.au/~npyner/Arduino/BT_2_WAY.ino

OK, the first thing you need to do is read the first post in the section and see how to enter code using the hash icon.

My apologies for not following the forum instructions correctly.

#define READINGCOUNT 25

//Global Variables
int _count; //index 
int _delayCount=0; //counter to generate delay for sending readings every X seconds
int _state; //state machine - current state
String _readings[READINGCOUNT] = {"43","63","44","47","50","46","44","60","52","47","51","50","49","63","57","52","57","51","47","44","43","42","42","42","42"};
char _btRxData; //Most recent received byte from BT Shield
String _btRxBuff=""; //Local buffer for received data
char _pcRxData; //Most recent received byte from PC (over serial)


void setup()
{
  //Initialise Serial Port to PC
  Serial.begin(9600);
  
  //Initialise BT Shield
  BluetoothInit();
  Serial.println("Bluetooth Hardware Initiated");
  
  Serial.flush();
  _count=0;
}

void loop()
{
  //If new byte of data to receive from BT Shield
  if(Serial1.available())
  {
     _btRxData = Serial1.read(); //Read it
     _btRxBuff += _btRxData;   //Add it to buffer
     Serial.print(_btRxData);  //Debug: Send to PC Console 
  }
  
  //If new byte of data to receive from PC 
  if(Serial.available())
  {
    _pcRxData = Serial.read(); //Read it
    Serial1.print(_pcRxData);  //Relay to BT Shield
  }
  
	//Check for disconnection
      if(_btRxBuff.indexOf("+BTSTATE:1") != -1) //BT STATE 1 indicates a disconnection
      {
            Serial.println("Debug: Disconnection Detected");
           
            Serial1.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable 
            delay(2000); // This delay is required.
            Serial1.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable 
            delay(2000); // This delay is required.
            
            Serial.println("Debug: Earpiece Is Inquiring Again");
            _btRxBuff=""; //Clear buffer
            _state=0;
      }
      
	  //Detect disconnect when remote device drops off (disconnection not properly indicated by remote device)
      if(_btRxBuff.indexOf("CONNECT:FAIL") != -1)
      {
            Serial.println("Debug: Error Occurred");
           
            Serial1.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
            Serial1.print("\r\n+INQ=0\r\n"); //make the slave bluetooth inquirable 
            delay(2000); // This delay is required.
            Serial1.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable 
            delay(2000); // This delay is required.
            
            Serial.println("Debug: Earpiece Is Inquiring Again");
            _btRxBuff="";
            _state=0;
      }

      
     
  //Main FSM logic
  switch(_state)
  {
    case 0:
      //Idle state (waiting for connection)
	  
      if(_btRxBuff.indexOf("+BTSTATE:4") != -1) //If successful connection detected?
      {
          //Connection has been established - clear local buffer
          Serial.println("Debug: Connection Established");
          _count=0;
          _delayCount=0;
          _btRxBuff="";
          _state=1;
      }
      break;
      
    case 1: 
		//State which starts sending readings
    
      //Send reading every X * 1ms   (current delay is 2 seconds)
	  //This method of delay avoids long "delay(2000)" at bottom, which would cause device to receive data 1 byte per second! (that wouldn't be good!)
      if(_delayCount == 2000) 
      {
        if(_count < READINGCOUNT) //Send the next reading in the readings array
        {
          Serial.println(_readings[_count]);
          Serial1.print(_readings[_count]);
          _count++;
          
        }
        else _count=0; //If reached end, reset
        
        _delayCount=0; //Reset delay counter
      }
      else _delayCount++;
      
      break;
      
    default:
      break;
  }
  
  //Common delay for each cycle (used in order to send data every X seconds)
  delay(1);
}

void BluetoothInit()
{  
  Serial1.begin(38400);
  Serial1.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode
  Serial1.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave"
  Serial1.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me
  Serial1.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here
  delay(2000); // This delay is required.
  Serial1.print("\r\n+LOSSRECONN=0\r\n");
  delay(2000);
  Serial1.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable 
  delay(2000); // This delay is required.
  Serial1.flush();
}

You didn't answer about the power supply

The operating voltage of the bluetooth module is 3.3V, so there is no problem with the power supply!

The code that I sent works perfectly on the other Bluetooth Board of the Seeed Studio Bluetooth Shield and it achieves pairing with the android tablet and when I run the app I can see the generated readings from the Pro Micro.

I have never heard of a HC-06 Keyes BT_BOARD v2.0 and Google apparently hasn't heard of it either but you do say it is an HC-06

It is a normal JY-MCU HC-06 Bluetooth Board but the BT_BOARD V2.0. I don't know whether different versions required different code.

Thank you

Heartfelt_Angel:
The operating voltage of the bluetooth module is 3.3V, so there is no problem with the power supply!
........
It is a normal JY-MCU HC-06 Bluetooth Board

I believe these are conflicting statements and you should check it again. If you are feeding the JY-MCU from the 3.3v Pro Micro or its supply, then it is a fair bet that you are feeding it 3.3v. Irrespective of this Keyes stuff, a "normal JY-MCU HC-06 Bluetooth Board" has the power supply requirement very clearly marked on the back, and it says 3.6 - 6v. This clearly implies that you are about 10% short of the minimum. This might not be an ironclad guarantee of disaster, but it is certainly a very good way of inviting it.

The code that I sent works perfectly on the other Bluetooth Board of the Seeed Studio Bluetooth Shield and it achieves pairing with the android tablet and when I run the app I can see the generated readings from the Pro Micro.

I submit that the best you can really say is that some of the code actually allows you to achieve your end but it is still junk and some, if not most, is redundant and speaks volumes about what is really going on.

Two cases in point:

  1. The HC-06 is a slave and cannot be anything else, so why are you attempting to set it up as a slave?
  Serial1.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode

I'm not sure, but I believe the same question might be asked even if it was a master.

  1. Since the HC-06 is a slave, no code in the Arduino can achieve pairing with an Android tablet. All the pairing is done by the Android and Arduino doesn't even need to be present for it to achieve that.

I guess that part of the problem is that the code is inherited from the Seed, which I believe does not use an HC-06, but suspect it would be junk on the Seed as well - at best, a mish-mash of demonstration stuff that is short on practical application. I suggest you ditch it all and start over.

If your HC-06 is what you imply it is, i.e. normal, the code I linked to will be sufficient to at least prove your equipment is kosher. Indeed I might add that if you don't get a result with the notes provided, it is very likely that you have a power problem.

is there a basic code to program the Pro Micro in order to generate and send readings through bluetooth to a custom android app

Once you have ditched all the junk and proven you gear kosher, Arduino essentially needs no more than

void loop()
{
gather data;
Serial.print (data);
}

which is more or less what everybody else does.

The custom Android app is, of course, down to you, and I guess that is what this is all about.

I would like to thank you for your time and your valuable information, I have connected my HC-06 with two different bluetooth android apps ( BlueTerm and Bluetooth Graphics) having as result a solid LED, which I guess it indicates a good connection. I used this code that you sent me:

/* This is a simple test for two way traffic via bluetooth 
   but you can try it first using the USB cable to the serial 
   monitor without the bluetooth module connected.
   
   Note that some bluetooth modules come set to a different baud rate.
   This means you need to alter the command
                Serial.begin(9600) accordingly
   Same goes for the setting in the bottom right corner on the 
   serial monitor */             

void setup()
{
    Serial.begin(9600);
    Serial.println("OK then, you first, say something.....");
    Serial.println("Go on, type something in the space above and hit Send,");
    Serial.println("or just hit the Enter key");
}
 
void loop()
{
  while(Serial.available()==0)
  {}

  Serial.println("");
  Serial.println("I heard you say:");
  while(Serial.available()>0)
  {
    Serial.write(Serial.read());// note it is Serial.WRITE
  }
  Serial.println("");
}

Can you please help me a bit further with the code that is required in order to make the Pro Micro generate some readings {"43","63","44","47","50","46","44","60","52","47","51","50","49","63","57","52","57","51","47","44","43","42","42","42","42"} and send them to the app?

Thank you again

OK, so it looks like all you needed was to clear the detritus off the decks, and you don't have a power problem but, IF you are feeding Bluetooth in the way I think you are, you may have a power problem in the future.

Yes, the solid LED does indicate a kosher pairing but that is all.

If the programme works, then clearly all is well.

Note that the programme serves no more purpose than to prove that your equipment and procedures are all OK. It is then just a case of sending Serial.println(data): as you would to the serial monitor. Like me, you probably don't need to listen for anything coming the other way.

Can you please help me a bit further with the code that is required in order to make the Pro Micro generate some readings {"43","63","44","47","50","46","44","60","52","47","51","50","49","63","57","52","57","51","47","44","43","42","42","42","42"} and send them to the app?

I'm afraid I have no idea what you mean by this, principally because I have no idea of what you are trying to do. I am only involved with data handling, not generation, i.e. I receive a reading from a sensor and pass that on to wherever. You appear to be doing something completely different. What you seem to have is a row of meaningless numbers, devoid of apparent purpose, and I don't understand the objective.

Thank you again for your quick reply.

I am indeed powering up the bluetooth with the Pro Micro, hopefully a problem will not occur soon.

I am working on a prototype medical micro device. This micro device will have sensors and it will be measuring the levels of a certain substance in the human body and at the same time sending this information (through bluetooth) to a Android app and a PC Base station. At this point, I am developing a demo device, where we just want to show how the measurements will be sent and displayed to the android app, because basically the sensors part is still under research. That is why i need a code to generate the numbers I sent you and make them appear (with a loop) on the app that we have developed, as if they are the actual measurements.

Thank you

OK so you are actually intending to do some data collecting and all those number are just dummies. I see there are 26 of them, which is almost too good to be true, and I guess somebody was thinking along the lines

setup
int a = 43
int b =63
.
.
int z = 42

loop
serial.print (a);
delay(1000);
serial.print(b);

etc. etc

Crude but should work

Goodnight.

Ok, I will give it a go! Thnx a lot

I'm having a similar problem.
I'm using a HC-05 BT module on a MEGA2560( running my sketch) and it pairs with my Android APP with no problems and am able to send data.(here the RXD of the BT is connected to TX0).
Now, when i connect the same BT module to a MICRO with the same sketch, it does not pair with the APP. I've even tried using separate power for the BT module (just in case the micro couldn't supply enough juice)(here the BT is connected to the TX, pin3). :stuck_out_tongue_closed_eyes:

Thanks.

Clearly, if you can get things to work OK with the Mega, there can't be anything fundamentally wrong, and you know mostly about what you are doing.

Now, when i connect the same BT module to a MICRO with the same sketch, it does not pair with the APP

But are you sure what the problem really is?

I submit he connection is a matter between Android and Bluetooth. For that purpose, it doesn't matter if Arduino is a Mega or a Micro, it's just there to supply the power and, since you already have alternative power, it needn't even be connected. You don't need Arduino until it comes to the time to send data.

So, is the LED blinking or steady?

Hi Nick,
Thanks for the quick reply.
When its not connected it is flashing every 0.5 secs.
It will connect to the APP for about 2 secs (not flashing) and disconnect. :astonished:
Thx

I'm afraid this is a bit beyond me. The problem may even be at the Android end

keyboard888:
When its not connected it is flashing every 0.5 secs.

This normal (surprise!)

It will connect to the APP for about 2 secs (not flashing) and disconnect. :astonished:

This suggests that a connection is made and then lost 2 seconds later, but I can only guess at the cause, and am probably no better at guessing than you are. I think the timing is important as 2 seconds is an eternity and certainly long enough to eliminate any confusion with the 2Hz blink. If you are doing this with the alternative power, that will confirm that this is not an Arduino problem.

I can only suggest you

  1. go back to the Mega, and power from Mega, to confirm there is no problem there. It will also confirm that all is kosher, or can be, at the Android end.

  2. then go to Micro with power from Micro, to confirm there really is a problem. You might find there isn't, and it was just some stupid mistake that only happens once.

:smiley: :smiley: :smiley:
Have to use Serial1 .....
Thanks Nick,
Good to have guys like you to give one the confidence to plug on. ]:smiley:

Sounds like it's one of those that happens once..........