How to properly use Bluetooth communication with Arduino and HC-05/06

Bluetooth Module HC-05 or HC-06 comes with Serial interface with default baudrate 9600 bits per second. It is easy to hook it up. I prefer to use hardware Serial if it’s possible. Arduino Mega 2560 has 3 spare hardware Serials, Arduino Micro or Pro Micro has one spare and regular Arduino Uno has no spare Serial. In this case You can use Software Serial library which likes to use interrup pins of Arduino Uno 2 and 3.  When You have already connected bluetooth to the Arduino it’s time to try it out.

    1. Include SoftwareSerial library
      #include <SoftwareSerial.h>
    2. Declare bluetooth object
      SoftwareSerial bluetooth(RX_PIN, TX_PIN); // usually pin 2 and 3
    3. Start serial communications
      bluetooth.begin(9600);
      Serial.begin(9600);
    4. Add receive and transmit functions to the void loop
      if (Serial.available() > 0) {
      bluetooth.write(Serial.read());
      }
      if (bluetooth.available() > 0) {
      Serial.print(char(bluetooth.read()));
      }

 

You want to make something complex sometimes like saving every received byte to the string and then displaying it as text.

  1. Declare string object outside any void
    String buffer = "";
  2. Add this code to the while loop
    
    if (bluetooth.available() > 0) {
      char rd = char(bluetooth.read());
      if (rd == '.') {
        Serial.println(buffer);
        buffer = "";
      } else {
        buffer += rd;
      }
    }