Raspberry Pi Serial Communication over Bluetooth LE using Adafruit Bluefruit LE Friend for Python Programming
Do you want to use the bluetooth interface for a Python programming project but you don't want to deal with the complexity involving bluetooth? This guide will help you.
The purpose of this guide is to demonstrate how to do write a program in Python which will do serial communication over Bluetooth for the Raspberry Pi.
The Adafruit Bluefruit LE Friend has FDTI chipset that works out of the box on Raspberry Pi which is useful for simplicity. (1)
This guide assumes you've just setup Rasbpian
and have done nothing else.
-
Run the raspberry pi configurator
$ sudo raspi-config
-
While following the GUI, please make sure the following is enabled:
1. SSH - enabled 2. Wifi - Enabled 3. Serial Login - Disabled 4. Serial - Enabled
-
Finish the installation and reboot the computer.
-
From your developer machine,
SSH
into your Raspberry Pi device. Please change xx to the IP address assigned.$ ssh -l pi 192.168.0.xx
-
Make sure everything is up to date.
$ sudo apt-get update $ sudo apt-get upgrade
-
Plug in the Adafruit Bluefruit LE Friend usb stick into your Raspberry Pi.
-
Make sure the DATA is set.
-
After plugging in the device, run the following commands and take a look at the output.
$ dmesg | grep tty $ tail /var/log/messages
-
Notice the
ttyUSB0
? This is the serial interface. We can write python code to interact with it as a serial inputut/output while the hardware does the heavy lifiting handling Bluetooth transmisstion. -
Lets create our bluetooth server on the Raspberry by installing our depedencies first:
$ sudo apt-get install python3-serial
-
Create our file
$ cd ~/ $ cat > bluetooth_server.py
-
Copy and paste the code below in your Raspberry Pi
from serial import Serial from time import sleep port = "/dev/ttyUSB0" ser = Serial(port, 9600, timeout=None) sleep(2) # wait for Arduino while True: try: byte_data = ser.readline() # print(byte_data) # For debugging purposes of outputting the raw data. string_data = byte_data.decode('UTF-8') # https://stackoverflow.com/questions/6269765/what-does-the-b-character-do-in-front-of-a-string-literal#6273618 print(string_data) # msg = ser.read(ser.inWaiting()) # read all characters in buffer # sleep(2); # print(msg) string_data = "Received message" byte_data = string_data.encode('UTF-8') ser.write(byte_data) except Exception as e: pass
-
Run the server.
$ python3 bluetooth_server.py
-
Now let's confirm everything works. If you have an
iOS
device then download the app called Adafruit Bluefruit LE Connect from the Apple AppStore. Or if you have anAndriod
device, then download the Adafruit Bluefruit LE Connect from the Google Store. -
Open up the App, click on Adafruit Bluefruit LE. Afterwords click UART.
-
Enter some text and send it.
-
You should see that data was successsfully sent!