Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Arduino

Bluetooth Messenger

5.00/5 (5 votes)
2 Aug 2018CPOL13 min read 22.8K   475  
Learn To Use HC-05 Bluetooth Component so you can communicate with your Arduino

Introduction

One of the most exciting things when working with Arduino is getting it to talk to other components. It is not always necessary (or preferable) to have the component connected to the Internet. That's where Bluetooth comes in nicely. There is a very inexpensive (and mostly) easy-to-use component (HC-05) that can be paired with your Arduino so you can control your Arduino remotely. Learning to use the component also provides a great entre into larger Arduino projects you may have in mind.

Background

The Bluetooth module we are going to use is very easy to use with the Arduino. You literally only need four wires to hook it up to your Arduino (VCC, GND, Tx (transmit), Rx (receive). Basically, when the module receives data, it writes it to the Tx pin, sending the data out to the Arduino (in via the Rx pin).

There are a number of things you need to work with a Bluetooth component:

  1. Bluetooth (BT) component (in this article, we are using the HC-05)
  2. A way to send messages over Bluetooth. In this article, we will use the Android app which I wrote for this specific purpose. It is named BTMessenger and I've placed the source code at my GitHub (https://github.com/raddevus/BTMessenger^). It's easy to use. You can type a message and press the [Send] button (more later).
  3. Understanding how the Bluetooth component is configured and how it can be paired with the device you will use to send messages to it. You can use the BT component straight out of the box with default settings (speed 9600 and PIN 1234, name=HC-05) but if you want to change the device to have a nice name and a different PIN, then you'll need to know how configure it. To configure the component, you have to wire it up in a special way and use a Serial app to send AT commands to it. (I will point you to an article I am writing so you'll know the ins & outs of this.)

Point of This Background

The main point I'm trying to make is:

It's very easy to get the HC-05 Bluetooth (BT) component set up and use it for the basics. However, it is quite difficult to customize the component. You will see that there is a lot of mis-information about the component out there and many of them from the numerous manufacturers work slighly different.

Why Not Bluetooth 4.x / BLE?

There are far more details to get BLE (Bluetooth Low Energy) working. I'm planning on doing a larger investigation on BLE in the future since it is wise to move to BLE so you can support iOS apps (iphone, ipad, etc.).

Parts List For This Article

  1. Arduino Uno - I use the Elegoo clone (https://amzn.to/2JOoiIp) about $11 USD
  2. I2C LCD - (https://amzn.to/2NBWl8S) I showed you how to use this in my other article (Discovering What Your Code Is Doing Using a 20x4 LCD With Your Nano[^]) about $10 USD
  3. Bluetooth component / HC-05 (https://amzn.to/2ABeAcQ) $8.99 USD
  4. Breadboard - I use these (https://amzn.to/2uVHteA) about $8.50 USD for 3
  5. Hook up wire: Here’s the wire pack I ordered and I am very happy with (https://amzn.to/2JsVKsz). About $20.

Let's get started using the HC-05 straight out of the box.

Wiring Up the HC-05 and Using It

The HC-05 can run off of 3.6V - 6V so your Uno will provide the correct power off the 5V pin. That makes things very easy. All you have to do is wire up your HC-05 like the following and connect your Uno to your USB port and you will see the HC-05 power up and start fast-blinking an LED.

Image 1

Why We Used Arduino Pins 10 and 11

The first thing you may be wondering about is why we used pins 10 and 11 for the Rx (receive) and Tx (transmit) pins. You may be familiar with the Uno and understand that pin 0 is the Rx (serial receive) and pin 1 is the Tx (serial transmit).

There are actually two reasons I chose to assign other digital pins to be our Rx and Tx.

  1. Uploading From IDE will Fail: When you go to upload your program to the Uno, the Arduino IDE will use the hardware serial Rx and Tx pins. When the IDE attempts to do that and the HC-05 is connected to those pins, you will find that the upload will fail. That's because the IDE believes the pins are in use and it cannot get a connection to them. Actually, it is just the Rx (pin 1) that it won't be able to connect to. But that means it cannot upload your sketch. It's easy to fix by removing the wire each time, but it is a pain when you're doing development. Using pin 10 for our Rx alleviates this problem.
  2. Using Serial Monitor Will Fail : Also if you want to use the Arduino IDE Serial monitor, you will not be able to since the Bluetooth device would be sitting on the hardware (pin 0 and pin 1) Rx and Tx pins. Connecting to pins 10 and 11 keeps 0 and 1 free for Serial Monitor use.

Get Your Wires Crossed: Rx => Tx and Tx => Rx

It is also important to notice that for the serial communication to work between the HC-05 and the Arduino, we need to make sure:

  1. HC-05 Tx pin is connected to Arduino Uno Rx pin
  2. HC-05 Rx pin is connected to Arduino Uno Tx pin

Take another close look at the first schematic and you'll plainly see that now. I placed the pins on the devices so the wires don't actually cross each other.

What Happens When Bluetooth Message is Sent or Received

You really have to wrap your head around this and think about how it works.

Bluetooth Receive Message

When the HC-05 device receives a message over Bluetooth, it writes that message to its Tx (transmit pin).

Since we want our Uno to receive the messages, we connect the HC-05 Tx pin to the Uno Rx pin (digital 10 in our case).

Bluetooth Send Message

When we want to send a message from the Bluetooth device, we will have the Uno write serial bytes to its Tx pin (digital 11). When we write data to the Uno Tx pin, it will be received by the HC-05 on its Rx pin. The HC-05 sends the data that it receives on its Rx pin by broadcasting it on the Bluetooth signal.

Now, let's write a very simple sketch to receive data and display it in the Serial Monitor.

First Sketch: Display Data In Serial Monitor

Take a look at the HC-05 component.

Image 2

You can see that it has six pins, but we only need to use four of them. There is also a button (top right of the first picture) that is used when you put the component into configuration mode.

On the back side, the pins are labeled for you. We only use the Rxd, Txd, GND and VCC.

Image 3

Here's what it looks like all wired up and running.

Image 4

You can see that the red LED on the HC-05 is on -- it is actually blinking fast indicating that it is ready to receive data.

Now, let's upload some code that will read bytes from Bluetooth and print them out in the Serial Monitor.

Here's the full code listing:

C++
#include <SoftwareSerial.h>

SoftwareSerial BT_Serial(10, 11);

void setup() {
  Serial.begin(19200);
  Serial.println("BT Messenger");
  BT_Serial.begin(38400);
}

void loop() {
  String outMsg;
  int incomingByte;
  byte byteCounter = 0;
  byte words[64];
  
  if (BT_Serial.available() > 0) {
    Serial.println("got data"); 
    incomingByte = BT_Serial.read();
    while (incomingByte > 0){
        words[byteCounter++] = incomingByte;
        Serial.print(incomingByte,DEC);    
        incomingByte = BT_Serial.read();
        Serial.print(" ");
      } // while
      Serial.println("");
      for (int x = 0; x < byteCounter; x++){
        outMsg += char(words[x]);
      } // for
      Serial.println(outMsg);
    } // if (BT_Serial.available()
} // loop()

Get the Code: BTMessenger_v001.zip

Download the code and upload it to your Uno and try it out.

Once you have it running, you'll go back to the Arduino IDE and open the Serial Monitor.

It's under [Tools]...[Serial Monitor]...

Image 5

When you select that menu item, the Serial Monitor window will open up. If your Uno is attached via USB cable and you've already uploaded the sketch, then it will print an initial message (BT Messenger).

Image 6

In the bottom right corner of Serial Monitor, notice that we have Carriage Return and LineFeed turned on [Both NL & CR]. We also have the speed set to [19200 baud].

If You See Odd Characters

If you see some odd output, it is probably because the baud rate doesn't match what we've set up in the sketch (19200).

Here's what mine looks like when I set it to 9600 baud. See those odd backwards question marks? If you see garbled output, it is almost always because you haven't matched the baud rate properly.

Image 7

Let's talk about the code now.

Software Serial

The first thing we do is include the SoftwareSerial library because we are using digital pins 10 and 11 instead of using hardware serial at pins 0 and 1.

Next, we instantiate a SoftwareSerial object by passing in the digital pin for Rx (10) and the digital pin to use for Tx (11). Keep in mind that we are configuring the Uno here.

C++
SoftwareSerial BT_Serial(10, 11); 

We name our Software Serial object BT_Serial so we can reference it throughout the code.

In the setup() method, we initialize both of the Serial devices we will use.

Configuring Software and Hardware Serial

Whenever you see the variable Serial, we are referencing the built-in hardware serial.

This is why we have to set up the Serial Monitor to 19200 because we initialize it to that value in our code.

Serial.begin(19200); // here we set the baud rate to 19200.

Serial.println("BT Messenger"); // here we print text onto the hardware serial. Since the Serial Monitor is connected to it, it will print it out.

Next, we have to initialize the speed of our Software Serial object also. Serial timing is very exact since it is sending bytes at a specific rate. That's why this value must match the speed that the Bluetooth (HC-05) is sent to send and receive data. We initialize it to 38400 because that is the default that the HC-05 is set to.

C++
BT_Serial.begin(38400);

Now, both the serial components are ready to go.

Next, we simply read the data off the Rx line of the Arduino and grab each byte one by one.

Before I explain the rest of the code, take a look at what the output looks like in Serial Monitor after I send a message.

Image 8

Get the Android App to Send Data

Of course, to send data to the device you write a program. I wrote a very simplified Android app which will let you type data in a TextEdit box and press the [Send] button. Here's a snapshot of the app.

Image 9

Download APK and Sideload BTMessenger

First, you will need to download the .apk. The easiest way to do that is point your phone or pad at the following URL on my web site: http://raddev.us/btmessenger.apk. When you point your Android device at that URL (from your browser), it will download the APK and ask you if you want to install the app. It isn't signed so it will warn you.

If you don't want to download the app, you can get the source code at my GitHub^ and build it and install it.

Pair Your Android Device With Your Bluetooth Component

After you download and install the app, don't start the app yet. First, you'll need to pair your device with the Bluetooth component. To do that, you need to:

  1. Power up your HC-05 - you have to do this so that the device can scan for the item. The item has to be on for it to find it.
  2. Next, you'll basically open the Bluetooth functionality on your device and then you may have to tell it to scan for new devices.

Here's what it looks like on my device. You can also see it is auto-scanning for new devices and their GUID (globally unique id) addresses are showing up first. After a bit, you will normally see the name of the device so you can identify it more easily.

You can also see I have a lot of paired Bluetooth devices. It's because I've been working with this Arduino Bluetooth stuff for a couple of years now off and on.

Image 10

When you click one that you want to pair, then a box will come up and you'll have to type the pin. The default is 1234 so you'll type that in and you'll be paired to the device. Once you are paired, you can run the app and the device will show up at the bottom so you can select it and send data to it.

Run the App

Select the name of your Bluetooth device in the bottom spinner (droplist). Yours will probably be named HC-05 which is the default. Mine is named superblue. Type in your message in the top TextEdit field and press the [Send] button.

Check If Data Has Arrived

Of course, the sketch continuously runs the loop() and checks to see if any data has arrived with the following line:

C++
if (BT_Serial.available() > 0)

The available() method is a SoftwareSerial function which returns a number of bytes that are in the serial buffer. There will be bytes in the serial buffer, if the Bluetooth device has received a message, because when the Bluetooth device receives a message, it writes those bytes to its Tx pin. Since the Tx pin of the Bluetooth device is connected to the Rx (receive pin) of the Uno, the Uno has bytes in its serial buffer.

The first thing the sketch does when it gets data is prints "got data" to the hardware serial output which shows up in the Serial Monitor. I do that just so I can know I'm in that part of the code, as a debugging message.

Read the Bytes Out of Serial Buffer

The serial buffer can be up to 64 bytes and we use the following line to read those bytes out and into our own byte buffer so we can do something with them.

C++
incomingByte = BT_Serial.read();

The read() method reads one byte at a time, so I put the sketch into a loop to read all of the available bytes out of the buffer.

Then I print each byte as its byte value with:

C++
Serial.print(incomingByte,DEC);  

That is the code that prints all of the digits on the line following the "got data" line in the Serial Monitor:

Image 11

After that, I convert each byte into a character and add it to the outMsg string and finally, we print the character-based message into the serial monitor.

That's really all there is to it. But now, you can see that you can send messages to your Arduino over Bluetooth.

The Challenges You May Encounter

There are a few challenges you may encounter and they are almost always related to having the wrong speed set up on something.

It may be that your HC-05 is defaulted to 9600. If that is true, you are going to get garbage output in the Serial Monitor and you'll need to change the line that sets it to 38400 to 9600. That means that instead of the following line in setup():

C++
BT_Serial.begin(38400);

You will have:

C++
BT_Serial.begin(9600);

That's all there is to it. This should get you going so you can begin to communicate over Bluetooth with your Arduino and control your Arduino from your phone by sending it various messages.

Other Bluetooth Information

Other things that you'll want to know is how to change the pin code and the name of your device. There is a way to do that and it isn't terribly difficult, but it does take another circuit setup and some different code. I'll cover this soon on my blog or here at CodeProject. See you then.

History

  • 2018-08-02: First publication

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)