2013-03-24T06:28:17Z

A cheap Bluetooth serial port for your Raspberry Pi

Posted by Miguel Grinberg under Raspberry Pi.

Raspberry Pi Bluetooth

While working on my Arduino based robot vehicle project the idea came to me that the Bluetooth module that I'm using as a remote control receiver for my robot would make a great addition to my Raspberry Pi.

In this article I describe how to enable the Raspberry Pi's serial port to talk to other devices over Bluetooth using this module.

Required hardware

The nice aspect of this project is that it requires very little hardware, most of the action happens in the software side. But of course we do need some hardware, which I list below:

  • A Raspberry Pi.

    If you have been living under a rock or in another planet for the last year or two and never heard of the Raspberry Pi then you should know that this is a credit card sized Linux computer created in the UK that sells for just $35 USD. I've got mine through Element 14.

  • A Bluetooth slave module

    This is a small and inexpensive Bluetooth to serial adapter that is mainly targeted to Arduino users. I've got mine from the Virtuabotix store at Amazon.com for $14.95. The Chinese electronics stores on Ebay sell it for less, but of course you have to wait longer to get it.

  • Four female-to-female breadboard wires

    If you buy the Bluetooth module from the Virtuabotix store at Amazon (link above) then you get the wires included with it. If you are buying from another place you may want to ask if wires are included or sold separately.

  • A computer or device with a Bluetooth terminal software

    To establish a communication with the Raspberry Pi over Bluetooth you need another device that can speak Bluetooth. If your computer has a Bluetooth adapter then you just need to find a terminal software that you can use to send and receive data, like HyperTerminal on Windows, or screen on OS X and Linux. A computer is not the only choice, though. For example, I will use my Android cell phone with the free BlueTerm app installed.

Wiring

The wiring is very simple and is better explained with a diagram:

Raspberry Pi Bluetooth

If you prefer to see it in table format, here are the four connections that you need to make:

RPi GPIO pinBT module pin
5V (Pin #2)VCC
GND (Pin #6)GND
TXD (Pin #8)RXD
RXD (Pin #10)TXD

Note that the TXD and RXD connections between the RPi and the Bluetooth module are crossed, this is what makes one end receive what the other end sends.

Raspberry Pi configuration

I'm going to assume you are running a recent release of Raspbian on your Raspberry Pi. If you are running another OS then you will need to find out how the changes below are done in your system.

By default the Raspberry Pi is configured to write boot time messages to the serial port, and also to start a login console on it. Unfortunately, the default baud rate that the RPi uses for its serial port is 115200 bps, while the Bluetooth module comes preconfigured from factory to 9600 bps.

It is easier to configure the RPi to use 9600 bps so we will try that first. There are two config files that need to be updated.

File /boot/cmdline.txt contains the kernel options that are used to boot the system. In my Raspbian based system this file contains the following options:

dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

The interesting options are console and kgdboc, because these configure the serial port device /dev/ttyAMA0 to 115200 bps. You need to change these two configurations to 9600 bps. After you make these changes the file should read:

dwc_otg.lpm_enable=0 console=ttyAMA0,9600 kgdboc=ttyAMA0,9600 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

The second configuration file is /etc/inittab. Inside this file you have to locate the following line:

T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

This tells the system to start a terminal on the serial port, and again it uses 115200 bps to configure the port. You have to change this line to use 9600 bps:

T0:23:respawn:/sbin/getty -L ttyAMA0 9600 vt100

Remeber that these are configuration files so they are not writable to the default pi user, to edit these files you have to use sudo. As far as text editors, Raspbian provides two, vi and pico. If you don't know either then you will probably be more confortable using pico. For example, to edit cmdline.txt with pico you would run the following command:

$ sudo pico /boot/cmdline.txt

The system will ask for your password and after that you will be able to make changes to this file. I recommend that you save original copies of these config files in case you make a mistake.

With those changes made the RPi is configured to talk to the Bluetooth module. If you now power up your Raspberry Pi you will notice that the LED in the Bluetooth module blinks rapidly. This is the sign that the Bluetooth module is ready and waiting to be paired with another device.

Connecting from a Bluetooth terminal

Now leave the RPi running with the Bluetooth module in its blinking state and go to the Bluetooth enabled computer or smartphone that you will connect to it. Your device should now find the Bluetooth module with the name linvor when you set it to discover devices.

If you are using an Android device with BlueTerm then start the app and from the app menu select "Connect device". Android does the baud selection automatically so you don't have to configure it. From a terminal software running in a computer it is likely that you will need to configure the speed, number of data bits per character, parity, and number of stop bits per character. The values you need to use are:

  • Speed: 9600 bps
  • Data bits: 8 bits
  • Parity: None
  • Stop bits: 1 bit

The Bluetooth module comes preconfigured with a PIN number. To complete the connection your computer or smartphone will ask you to enter this PIN. The factory default PIN is 1234.

The LED in the Bluetooth module will now stop blinking and remain lit, indicating that it has made a connection.

And here comes the fun part. You need to reboot the Raspberry Pi so that the new serial port settings take effect. To reboot the RPi run the following command in a local or network shell:

$ sudo reboot

Now watch the Bluetooth terminal on your PC or smartphone while the Pi reboots. Boot messages should be appearing on your terminal, and as soon as the RPi is up you should get a login prompt there as well.

You can now login from your Bluetooth terminal and use the command line prompt as you normally would over a local or network shell.

Below is a short video that shows my Raspberry Pi connected to my Android smartphone:

Direct serial port access

While you can't deny there is a coolness factor in being able to run a Raspberry Pi from a smartphone, let's be honest, that isn't extremely useful. But having a wireless serial connection into the RPi can be useful for regular applications, for example for debugging or for remote control.

To be able to use the serial port from a user application running in the Raspberry Pi we first need to tell the system to not use it as a console. To do this we need to go back to the two configuration files we touched before. I once again recommend that you back up your config files before changing them, in case things don't work out well and you need to revert the changes.

In file /boot/cmdline.txt we are going to remove the two serial references by taking away the first console and kgdboc sections:

dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

And in file /etc/inittab we will comment out the serial console task:

#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

After making these changes reboot the system so that they take effect. With these changes the RPi will not use the serial port at all, so the port will be free to any application that wants to use it as /dev/ttyAMA0.

If you want to play with sending and receiving data through the serial port then you can install minicom into your RPi using the following command:

$ sudo apt-get install minicom

And then you can open a terminal on the serial port with this command:

$ minicom -b 9600 -o -D /dev/ttyAMA0

Anything you type inside the minicom terminal will be sent to the serial port, and anything the other side sends will be displayed.

Configuring the Bluetooth module

The Bluetooth module comes preconfigured from the factory with a set of defaults, which are:

  • Baud rate: 9600
  • Bluetooth ID: linvor
  • PIN: 1234

But these values can be changed by sending special commands through the communication channel. Now that the Raspberry Pi is connected to the module we can try this.

These special commands that configure the Bluetooth module can be sent from a connected remote device, or they can be sent from the local system, in this case the Raspberry Pi. Since the Raspberry Pi is the star of the article I'm going to also use it to do the configuration.

Here is a quick summary of the most useful configuration commands:

CommandDescription
ATTest the communication with the Bluetooth module.
AT+VERSIONReport the module's version number
AT+NAMEnameChange the Bluetooth ID to name (maximum 20 characters).
AT+PINnnnnChange the PIN to nnnn, which must be a four digit number.
AT+BAUDnChange the baud rate. Use one of the following values for n:
2: 2400bps
3: 4800bps
4: 9600bps
5: 19200bps
6: 38400bps
7: 57600bps
8: 115200bps

One tricky aspect of sending these commands is that the Bluetooth module has a very short timeout, so all the characters in a command must be entered really quickly. The safest way to get the entire command in time is to type it in a text editor window and then use copy/paste to send it really fast.

If your Raspberry Pi session is local, then there is no clipboard support unless you work inside the X environment, so you will need to run startx and then open a Terminal window. If you are using a remote shell over the network then you can use the clipboard in your host operating system.

To send the commands we can use minicom. So let's fire it up one more time:

$ minicom -b 9600 -o -D /dev/ttyAMA0

Note that it isn't necessary to have a connection to do this, so you can do this while the Bluetooth module is in its blinking state.

You now need to use any method to get the string AT into the clipboard, and then hit paste inside the minicom window to send the command to the module.

When you send AT the module should respond with this in the minicom window:

OK

If you get this response then you know that everything is all right. If you don't get a response then for some reason the Raspberry Pi is unable to communicate with the Bluetooth module.

When I send AT+VERSION to the module I get the following response:

OKlinvorV1.5

To change the baud rate to the fastest rate of 115200 we need to issue the command AT+BAUD8, and the module will respond with:

OK115200

Because the baud rate was changed now the communication will break, and we will need to exit and restart minicom with the updated speed:

$ minicom -b 115200 -o -D /dev/ttyAMA0

To change the name of the module to MyBT we must issue the command AT+NAMEMyBT, and the module will respond with:

OKsetname

And to change the PIN to 4321 the command is AT+PIN4321 and the response from the Bluetooth module will be:

OKsetPIN

Note that when the name and/or the PIN change the module requires a power cycle for the changes to take effect.

Also don't forget that if you change the baud rate and later want to reestablish the serial console you will need to change the two config files to reflect the new baud rate you have selected in the Bluetooth module.

Conclusion

I hope this article gives you some ideas to bring new life to the serial port in your Raspberry Pi. If you have any questions feel free to ask below in the comments!

Miguel

74 comments

  • #51 Satish Gunjal said 2015-06-09T13:51:26Z

    I am using HC-05 bluetooth module. Want to enable two way communication with my android phone. But unable to go pass the device inquiry step... Please help me to make it work....

    [b]Python script:[/b]

    from bluetooth import *

    print("performing inquiry...")

    nearby_devices = discover_devices()

    print("found %d devices" % len(nearby_devices))

    for addr, name in nearby_devices: try: print(" %s - %s" % (addr, name)) except UnicodeEncodeError: print(" %s - %s" % (addr, name.encode('utf-8', 'replace')))

    [b]Above python script returns error:[/b]

    Traceback (most recent call last): File "pi_bt_inquiry.py", line 12, in nearby_devices = discover_devices() File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 17, in discover_devic es sock = _gethcisock () File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 226, in _gethcisock raise BluetoothError ("error accessing bluetooth device") bluetooth.btcommon.BluetoothError: error accessing bluetooth device

  • #52 Miguel Grinberg said 2015-06-09T18:09:50Z

    @Satish: I'm not sure if you can manage the bluetooth module directly from Python. I recommend that you take the approach I show above, which is to connect it to your phone and then treat it as a serial port (i.e. using pyserial).

  • #53 Korean student said 2015-06-12T09:37:53Z

    thanx!! u r smart!! it helps me very much!!!

  • #54 Samuele said 2015-07-05T21:41:27Z

    Congratulation for your post but my question is: I need to use USB bluetooth dongle mounted on raspberry and connect it with a external bluetooth HC-05. Can you help me ? I had installed bluetooth bluez-utils blueman but is possible for me to pairing with passoword but i not understand how to connect it. Kind regards Samuele

  • #55 Miguel Grinberg said 2015-07-05T22:13:55Z

    @Samuele: I haven't used any USB bluetooth dongles with the Pi, so I don't know the answer to your question. Sorry.

  • #56 Nora said 2015-07-11T23:40:08Z

    can i use it to receive reading from a sensor?

  • #57 Miguel Grinberg said 2015-07-16T05:59:54Z

    @Nora: only if the sensor also has bluetooth.

  • #58 Luis said 2015-08-31T08:29:55Z

    What version of bluetooth does use this device? Is this compatible with smart bluetooth devices? Thank you!

  • #59 Miguel Grinberg said 2015-09-01T23:14:29Z

    @Luis: I believe the dongle I used for this article is Bluetooth 2.0.

  • #60 loic said 2016-02-09T20:33:33Z

    Hi Miguel, nice article, and very clear. When I'm using Blueterm I can pair with m BT module. But I only get one line : "Uncompressing Linux... done, booting the kernel." And after that, nothing is outputing. Do you have any idea why I don't get the startup log? (I think it's because on raspbbian, they display the raspberry icon on top of the boot log)

  • #61 Miguel Grinberg said 2016-02-09T22:35:38Z

    @loic: Not sure. Maybe something changed in recent releases of Raspbian, I haven't done this in some time. It could be that the configuration is different these days.

  • #62 Alessandro said 2016-02-13T16:21:15Z

    Great tutorial, i would like to use the bluetooth to send some command to the console, is it possible to disable the user and password request?

  • #63 Miguel Grinberg said 2016-02-14T20:07:34Z

    @Alessandro: you can probably build some sort of service on the Pi that listens to commands and runs them, but it is a really bad idea to remove security.

  • #64 johnskap said 2016-02-26T00:07:58Z

    wow !! super guide with a lot of good and helpful information !!!!

  • #65 KK said 2016-03-01T20:37:41Z

    Hey, is there any way to connect the bluetooth to a smartphone without the pairing process? i want to be able to connect different devices to the raspi without having to constantly pair the devices. Is this possible?

  • #66 Miguel Grinberg said 2016-03-05T03:05:51Z

    @KK: probably not with bluetooth. Maybe you can build some custom cable that can do it, but I don't know enough about his to give you pointers.

  • #67 Mars said 2017-06-05T22:09:58Z

    Can I now connect two devices to the rpi via that ble module? Or just one?

  • #68 Miguel Grinberg said 2017-06-06T03:44:07Z

    @Mars: You can, but only one at a time.

  • #69 Trevor said 2017-07-18T05:32:12Z

    With HC 05 modules you rmethod of interfacing with bluetooth was fine on early raspis but on the B+ no inittab was included have you update your system to run on B+ jessie and PI 3 using HC05 modules

  • #70 Miguel Grinberg said 2017-07-18T20:15:40Z

    @trevor: I have not looked at how this needs to be updated for the newer Pis yet, sorry.

  • #71 Paul said 2017-08-16T14:49:37Z

    Hi, I make this project with Rb2 and bluetooth XM-15B. I've a problem - I can't see inittab file and my cmdline has only -"dwc_otg.lpm_enable=0 console=tty1 root=PARTUUID=28636785-02 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait" Where i must change parameters?

  • #72 Miguel Grinberg said 2017-08-16T19:43:21Z

    @Paul: This is a four year old article. You will need to adapt the changes to current versions of Raspbian (or the OS that you are using if it is different). I haven't done any work on this for a while, so I don't know what the changes are.

  • #73 Nithin Thimmaiah said 2019-05-14T09:04:25Z

    Hi Miguel,

    I am using raspberry Pi3 which has a built in bluetooth. I get connected from Blueterm app and when i reboot, it gets disconnected. Meanwhile, in your video, I see that, your not connected with Monitor. So how did you reboot? Since no monitor, you cannot reboot from a local or network shell.

  • #74 Miguel Grinberg said 2019-05-14T10:46:19Z

    @Nithin: Not sure if you noticed, I've done this 6 years ago. As far as I can recall, I issued the reboot from a SSH session I had open over Wi-Fi.

Leave a Comment