Controlling Raspberry Pi GPIO using Android App over Bluetooth

raspberry pi

ByJayant 23

Controlling Raspberry Pi GPIO using Android App over Bluetooth

Raspberry Pi is very popular for IoT projects because of its seamless ability of wireless communication over internet. Raspberry Pi 3 has inbuilt Wi-Fi and Bluetooth, and Bluetooth is a very popular wireless communication Protocol. So today we are going to Control Raspberry Pi GPIO Pin through an Android app using Bluetooth.

Here we are using Raspberry 2 Pi Model B which don’t have inbuilt Bluetooth, so we are using a simple USB Bluetooth dongle. Apart from that we only need a resistor (220R) and a LED to demonstrate the GPIO controlling. Here we are using RFCOMM Bluetooth protocol for wireless communication.

Programming for Bluetooth in Python follows the socket programming model and communications between the Bluetooth devices is done through RFCOMM socket. RFCOMM (Radio Frequency Communication) is a Bluetooth Protocol which provided emulated RS-232 serial ports and also called as Serial Port Emulation. Bluetooth serial port profile is based on this protocol. RFCOMM is very popular in Bluetooth applications because of its wide support and publically available API. It is bound to L2CAP protocol.

We have also used Bluetooth module HC-06 in our previous project: Voice controlled LEDs using Raspberry Pi. Also check our previous Raspberry Pi Projects along with some good IoT Projects.

 

Installing Required Packages for Bluetooth Communication:

Before start, we need to install some softwares for setting up Bluetooth communication in Raspberry Pi. You should have a Raspbian Jessie installed memory card ready with Raspberry Pi. Check this article to install the Raspbian OS and getting started with Raspberry Pi. So now we first need to update the Raspbian using below commands:

sudo apt-get update
sudo apt-get upgrade

 

Then we need to install few Bluetooth related packages:

sudo apt-get install bluetooth blueman bluez

Then reboot the Raspberry Pi:

sudo reboot

BlueZ is a open source project and official Linux Bluetooth protocol stack. It supports all the core Bluetooth protocols and now become part of official Linux Kernel.

Blueman provides the Desktop interface to manage and control the Bluetooth devices.

 

Finally we need python Library for Bluetooth communication so that we can send and receive data through RFCOMM using Python language:

sudo apt-get install python-bluetooth

 

Also install the GPIO support libraries for Raspberry Pi:

sudo apt-get install python-rpi.gpio

 

Now we are done with installing required packages for Bluetooth communication in Raspberry Pi.

 

Pairing Devices with Raspberry Pi over Bluetooth:

Pairing Bluetooth Devices, like mobile phone, with Raspberry Pi is very easy. Here we have paired our Android Smart phone with Raspberry Pi. We have previously installed BlueZ in Pi, which provides a command line utility called “bluetoothctl” to manage our Bluetooth devices. But before that, connect your USB Bluetooth dongle with Raspberry Pi and check that whether it is detected or not, by using below command:

lsusb

detecting-usb-bluetooth-dongle-in-raspberry-pi

 

Now open the bluetoothctl utility by below command:

sudo bluetoothctl

You can check all the commands of bluetoothctl utility by typing ‘help’. For now we need to enter below commands in given order:

[bluetooth]# power on
[bluetooth]# agent on
[bluetooth]# discoverable on
[bluetooth]# pairable on
[bluetooth]# scan on

After the last command “scan on”, you will see your Bluetooth device (Mobile phone) in the list. Make sure that your mobile has Bluetooth turned on and visible by nearby devices. Then copy the MAC address of you device and pair it by using given command:

pair <address of your phone>

Then you will be prompted for Passcode or Pin in your Terminal console then type passcode there and press enter. Then type the same passcode in your mobile phone when prompted and you are now successfully paired with Raspberry Pi. We have also explained this whole process in our Video given at the end.

bluetooth-paring-android-phone-with-raspberry-pi

 

As told earlier, you can also use Desktop interface to pair the Mobile phone. After installing Blueman, you will see a Bluetooth icon in right side of your Raspberry Pi desktop as shown below, using which you can easily do the pairing.

desktop-interface-for-paring-android-phone-with-raspberry-pi

 

Circuit Diagram:

Circuit diagram is very simple, we just connected a LED to PIN 40 (GPIO 21) of Raspberry Pi with a resistor of 220 Ohm:

controlling-raspberry-pi-GPIO-using-android-circuit

 

Controlling LED with Android App BlueTerm:

Now after paring the Mobile Phone, we need to install a Android App for communicating with Raspberry Pi using a Bluetooth Serial Adapter. As told earlier RFCOMM/SPP protocol emulates serial communication over Bluetooth, so we installed here BlueTerm App which supports this protocol.

BlueTerm-Android-app-for-controlling-raspberry-pi-GPIO

You can also use any other Bluetooth Terminal App which supports communication via RFCOMM socket.

Now after downloading and installing the BlueTerm App, run the below given Python Program from the terminal and connect the paired raspberrypi device from the BlueTerm App at the same time.

 connecting-BlueTerm-android-app-with-raspberry-pi

After successful connection you will see connected:raspberrypi at the top right corner of the App as shown below:

controlling-raspberry-pi-GPIO-with-python-over-bluetooth BlueTerm-android-app-for-controlling-raspberry-pi-GPIO                

Now you can just enter ‘1’ or ‘0’ from the BlueTerm app to make the GPIO pin HIGH and LOW respectively, which in turns switch ON and OFF the LED connected to this pin. Press ‘q’ to exit the program. You can use Google Voice Typing Keyboard to control the GPIO using your Voice. Check the complete demo in the Video given at the end.

So this is how you can wirelessly control the GPIO Pin using an Android App over Bluetooth. Also check How to use Bluetooth with Arduino.

 

Programming Explanation:

Python Program for Controlling Raspberry Pi GPIO with Android App is very simple and self-explanatory. Only we need to learn little bit about the code related to Bluetooth RFCOMM communication. First we need to import the Bluetooth socket library which enables us to control Bluetooth with Python language; we have installed the library for the same in the previous section.

import Bluetooth

 

Below is the code responsible for Bluetooth communication:

server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
 
port = 1
server_socket.bind(("",port))
server_socket.listen(1)
 
client_socket,address = server_socket.accept()
print "Accepted connection from ",address
while 1:
 
 data = client_socket.recv(1024)

Here we can understand them line by line:

server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM ): Creating socket for Bluetooth RFCOMM communication.

server_socket.bind(("", port):- Server binds the script on host '' to port.

server_socket.listen(1): Server listens to accept one connection at a time.

client_socket, address = server_socket.accept(): Server accepts client’s connection request and assign the mac address to the variable address, client_socket is the client’s socket

data = client_socket.recv(1024):  Receive data through the client socket client_socket and assign it to the variable data. Maximum 1024 characters can be received at a time.

 

Finally after all the programming, close the client and server connection using below code:

client_socket.close()
server_socket.close()

 

All the other code is easy and self-explanatory. Check the full code below. Try to modify this project and you can use it to control many other things wirelessly, like using Relays you can control the home appliances or can also control a Robot car through android phone.

Recommended TI Whitepapers

Code

import bluetooth
import RPi.GPIO as GPIO        #calling for header file which helps in using GPIOs of PI
LED=21
 
GPIO.setmode(GPIO.BCM)     #programming the GPIO by BCM pin numbers. (like PIN40 as GPIO21)
GPIO.setwarnings(False)
GPIO.setup(LED,GPIO.OUT)  #initialize GPIO21 (LED) as an output Pin
GPIO.output(LED,0)
 
server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
 
port = 1
server_socket.bind(("",port))
server_socket.listen(1)
 
client_socket,address = server_socket.accept()
print "Accepted connection from ",address
while 1:
 
 data = client_socket.recv(1024)
 print "Received: %s" % data
 if (data == "0"):    #if '0' is sent from the Android App, turn OFF the LED
  print ("GPIO 21 LOW, LED OFF")
  GPIO.output(LED,0)
 if (data == "1"):    #if '1' is sent from the Android App, turn OFF the LED
  print ("GPIO 21 HIGH, LED ON")
  GPIO.output(LED,1)
 if (data == "q"):
  print ("Quit")
  break
 
client_socket.close()
server_socket.close()

Video

Get Our Weekly Newsletter!

Subscribe below to receive most popular news, articles and DIY projects from Circuit Digest

Comments

  • Tom's picture
    Tom
    May 09, 2017

    I can't seem to get the pairing to work. When I type in "pair" and then the address that comes up for my phone, i get the error "org.bluez.error.AlreadyExists". Any help for how to work this would be very much appreciated.

  • Will's picture
    Will
    Aug 19, 2017

    Unpair the device before you try to connect

  • Kotz's picture
    Kotz
    Sep 05, 2017

    nice work. I couldnt type anything in Blue term app ??
    can i get rid of it ?

  • Aswinth Raj's picture
    Aswinth Raj
    Sep 06, 2017

    Yes you can use any Bluetooth App on your mobile. "Bluetooth Terminal" is also a good app

  • gowtham's picture
    gowtham
    Nov 22, 2017

    Hey,

    I've tried with python, its working perfectly. But when I switch to python3 its telling that import bluetooth no module found

  • FJ's picture
    FJ
    Nov 30, 2017

    can I know what is the full name of the usb Bluetooth dongle type that being use? I plan to buy it.

  • Sofia's picture
    Sofia
    Dec 14, 2017

    What should I do if the message is "org.bluez.Error.Blocked"?

  • arvind's picture
    arvind
    Dec 19, 2017

    hi
    i am getting error in this code plz anyone assist me to know about it
    error is below

    Traceback (most recent call last):
    File "/home/pi/bluetooth.py", line 1, in <module>
    import bluetooth
    File "/home/pi/bluetooth.py", line 10, in <module>
    server_socket=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
    AttributeError: module 'bluetooth' has no attribute 'BluetoothSocket'

  • Aswinth Raj's picture
    Aswinth Raj
    Dec 21, 2017

    Did you download the bluetooth librarey? If not follow these steps below, you should enter these commands on your cmd promt 

    we need python Library for Bluetooth communication so that we can send and receive data through RFCOMM using Python language:

    sudo apt-get install python-bluetooth

     

    Also install the GPIO support libraries for Raspberry Pi:

    sudo apt-get install python-rpi.gpio

     

  • Ashok kumar Dhandapani's picture
    Ashok kumar Dha...
    Jul 10, 2018

    even i have same attribute error: module 'bluetooth, has no attribute 'bluetoothsocket'
    have you fixed this error

  • Loris's picture
    Loris
    Dec 22, 2017

    Can you help me with this message? thank you

    pi@raspberrypi:~ $ sudo python GpioOverBluetooth.py
    Traceback (most recent call last):
    File "GpioOverBluetooth.py", line 13, in <module>
    server_socket.bind(("",port))
    File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 140, in bind
    return self._sock.bind (addrport)
    _bluetooth.error: (98, 'Address already in use')

  • daeungdaeung's picture
    daeungdaeung
    Jul 26, 2018

    I have had same issues.
    plz help us....

  • joao 's picture
    joao
    Jan 10, 2018

    can you help me with this message?

    connect failed-no usable services on this device android

  • maoz-th's picture
    maoz-th
    Mar 03, 2018

    you made my day.

    i start study raspberry pi on yesterday.
    i made pi communicate to smartphone over the HTTP it work fine then i think may it drain the battery
    so i use my day looking for tutorial, watch video, read article do follow instruction so many hours with no lucky.

    then i found you in YouTube that link to here, and it works!

    so thank you.

    PS. I'm java(Webapp)Developer

  • Saad's picture
    Saad
    Aug 10, 2018

    Good to know that you got it working.
    I wanted to know can you send strings from app to pi.

  • Nikith Sai's picture
    Nikith Sai
    May 08, 2018

    server_socket.bind(("",port))
    File "/usr/lib/python2.7/dist-packages/bluetooth/bluez.py", line 140, in bind
    return self._sock.bind (addrport)
    _bluetooth.error: (98, 'Address already in use')

    I tried a lot but I was getting this error repeatedly. If anyone has the solution please do reply here.

    Thank you in advance.

  • Sandro Ivankio's picture
    Sandro Ivankio
    May 17, 2018

    I was having the same issue.
    Only worked for me when I wrote the MAC Adress of my device between the quotation marks on the line:
    server_socket.bind(("",port))

    I suspect that is something related to the use of Wifi and Bluetooth simultaniously.

  • Ashok kumar Dhandapani's picture
    Ashok kumar Dha...
    Jul 08, 2018

    even after i copied my mac address it is showing the same error

  • Sandro Ivankio's picture
    Sandro Ivankio
    May 16, 2018

    Nothing happens when trying to connect via BlueTerm.
    After pressing Ctrl+C on RP terminal, got the following lines:

    Traceback (most recent call last):
    File "GPIO_Bluetooth.py", line 17, in <module>
    client_socket,address = server_socket.accept()
    File "/usr/local/lib/python2.7/dist-packages/bluetooth/bluez.py", line 167, in accept
    client, addr = self._sock.accept ()
    KeyboardInterrupt

  • Julia's picture
    Julia
    May 17, 2018

    hey guys,
    my phone is conected with the pi, it is ok, but when i press the numbers, in my python shell shows Received: b'1'
    Received: b'0'
    can anyone help me with this?

  • Aitor's picture
    Aitor
    Oct 07, 2018

    I had the same problem. I got it working by changing this: if (data == "0") by this: if (data == b'0').

    I hope it works for you too!!!!

  • ashwin's picture
    ashwin
    Jun 01, 2018

    Will this work in Raspberry pi 3, if I want to use the internal bluetooth?
    what if I want to us the internal bluetooth and the external UART port(TTYAMA0) for a GSM module simultaneously. What should I do? Someone please hekp me with this.
    Thanks in advance.

  • Aitor's picture
    Aitor
    Oct 07, 2018

    Yes, it will perfectly work on Raspberry pi 3 internal Bluetooth, I have one and I made it work. Thing is that Rpi has only one UART interface: UART0. So you would have to choose between Bluetooth or the UART port. Anyway, you could buy a USB to UART controller and use it for the GSM module, and use at the same time the internal Bluetooth.

    Hope it helps!!!

Log in or register to post Comment