Using BlueTerm to Communicate Between an Android Device and Raspberry Pi Over BLE

Ingredients

Android Device
Raspberry Pi with header (Zero W is what is used for this tutorial)
MicroSD card to store Raspbian OS
Short wires
Resistors (one 220 Ohm and one 4.7k Ohm)
Breadboard
LED
Temperature sensor (DS18B20)

Raspberry Pi Setup

For setting up the Raspberry Pi headless over Wifi follow the directions here:

https://desertbot.io/blog/setup-pi-zero-w-headless-wifi

For setting up the Raspberry Pi over USB follow the directions here:

https://desertbot.io/blog/ssh-into-pi-zero-over-usb

For setting up Bluetooth on the Raspberry Pi follow the directions here:

https://pimylifeup.com/raspberry-pi-bluetooth/

Pairing the Android Device with the Raspberry Pi

First you will need to put your Android device in Bluetooth pairing mode.
Next on the Raspberry Pi type in the following commands in bold:

pi@raspberrypi:~ $ sudo bluetoothctl
[bluetooth]# agent on
[bluetooth]# default-agent
[bluetooth]# scan on
[bluetooth]# scan off

Next find the Bluetooth address of your Android device in the scan results. The Bluetooth address will look something like XX:XX:XX:XX:XX:XX and will be displayed next to your Android device name in the scan results. Type in the following command on your Pi where the X’s are your Bluetooth address.

[bluetooth]# pair XX:XX:XX:XX:XX:XX
[bluetooth]# paired-devices

The paired-devices command should display your Android device if successfully paired. Next exit out of Bluetooth device configurations.

[bluetooth]# exit

If you weren’t able to follow along, this video is a useful demonstration of pairing the Raspberry Pi with another device:

https://www.youtube.com/watch?v=sEmjcgbmoRM

Setting Up and Connecting the Hardware to the Raspberry Pi

For this tutorial you will be connecting the Pi to a LED and a temperature sensor. You will be able to turn a LED on or off or get the temperature of the room using an Android app called BlueTerm.

The first step is to connect the LED, temperature sensor, resistors, and wires to the breadboard.

The 220 Ohm resistor needs to connect to the long end (+) of the LED. The short end (-) of the LED will be connected to a black wire. The other side of the resistor will be connected to a red wire.

The three pins of the temperature sensor (DS18B20) need to be connected to the breadboard. With the rounded side facing you, a 4.7k Ohm resistor will need to connect the left most pin and middle pin. The left most pin is power and so a red wire should be connected to it. The middle pin is data and so a yellow wire will connect to it. The right most pin is ground and so a black wire will connect to it.

Here is a picture of everything connected together:

Once the breadboard is connected together, the wires need to be connected to the correct pins on the Raspberry Pi. The red wire connected to the 220 Ohm resistor needs to be connected to Pin# 33 on the Pi. The black wire connected to the LED needs to be connected to Pin# 34 on the Pi. The red wire connected to power on the temperature sensor needs to be connected to Pin# 4 on the Pi. The yellow wire connected to data on the temperature sensor needs to be connected to Pin# 7 on the Pi. The black wire connected to ground on the temperature sensor needs to be connected to Pin# 6 on the Pi. Below is a picture of the wires connected to the Pi:

A diagram of the Raspberry Pi pin numbers can be found here:

https://pi4j.com/1.2/pins/model-zerow-rev1.html

Setting Up and Running the Python Script on the RPi

Once the hardware is set up, the next step is to add the Python script file to the Raspberry Pi. Use your favorite text editor to add the following Python code to your Raspberry Pi. Name the file “bluetooth_demo.py”.

import os
import glob
import time
import bluetooth
import RPi.GPIO as GPIO

base_dir = ‘/sys/bus/w1/devices/‘
device_folder = glob.glob(base_dir + ’28*’)
device_file = device_folder[0] + ‘/w1_slave’

def read_temp_raw():
	f = open(device_file, ‘r’)
	lines = f.readlines()
	f.close()
	return lines

#Celcius Calculation
def read_temp_c():
	lines = read_temp_raw()
	while lines[0].strip()[-3:] != ‘YES’:
		time.sleep(0.2)
		lines = read_temp_raw()
	equals_pos = lines[1].find(‘t=‘)
	if equals_pos != -1:
		temp_string = lines[1][equals_pos+2:]
		temp_c = int(temp_string) / 1000.0
		temp_c = str(round(temp_c, 1))
		return temp_c

#Fahrenheit Calculation
def read_temp_f():
	lines = read_temp_raw()
	while lines[0].strip()[-3:] != ‘YES’:
		time.sleep(0.2)
		lines = read_temp_raw()
	equals_pos = lines[1].find(‘t=‘)
	if equals_pos != -1:
		temp_string = lines[1][equals_pos+2:]
		temp_f = (int(temp_string) / 1000.0) * 9.0 / 5.0 + 32.0
		temp_f = str(round(temp_f, 1))
		return temp_f

host = “”
port = 1

led_pin = 13
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)

server = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
print(‘Bluetooth Socket Created’)

try:
	server.bind((host, port))
	print(“Bluetooth Binding Completed”)
except:
	print(“Bluetooth Binding Failed”)

server.listen(1)

client, address = server.accept()

print(“Connected To”, address)
print(“Client:”, client)

try:
	while True:
		client.send(“Input 0 = OFF, 1 = ON, 2 = TEMP:”)

		data = client.recv(1024)
		print(data)

		if data == “0”:
			GPIO.output(led_pin, GPIO.LOW)
			send_data = “\nLight Off\n”
		elif data == “1”:
			GPIO.output(led_pin, GPIO.HIGH)
			send_data = “\nLight On\n”
		elif data == “2”:
			send_data = “\nTemp (C): “ + read_temp_c() + “\nTemp (F): “ + read_temp_f() + “\n”
		else:
			send_data = “\nInvalid Input\n”

		client.send(send_data)
except:
	client.close()
	server.close()
finally:
	GPIO.cleanup()

The Python code sets up the pins on the Pi, turns the Pi into a Bluetooth server, and sets up the commands to communicate with the Pi.

A command of “0” will turn the LED off.
A command of “1” will turn the LED on.
A command of “2” will get the temperature of the room in Celsius and Fahrenheit.


Next, exit out of the text editor and run the Python script by entering:

pi@raspberrypi:~ $ python bluetooth_demo.py

Final Step: Download BlueTerm on the Android Device, Connect to the Raspberry Pi, and Run Commands

On your Android device, download the app BlueTerm from the Google Play store located here:

https://play.google.com/store/apps/details?id=es.pymasde.blueterm&hl=en_US

Next, connect your Android device to the Raspberry Pi by clicking on the Connect Device button and selecting the Raspberry Pi from the Paired Devices list.

Once the Android device is connected to the Pi, you may start to send commands (0, 1, or 2) through BlueTerm to the Pi to turn the LED on/off or get the temperature of the room in Celsius and Fahrenheit.