Bluetooth Communication with Python

Loading

Bluetooth communication allows wireless data transfer between devices like PCs, smartphones, microcontrollers (ESP32, Raspberry Pi), and IoT devices. Using Python, we can establish Bluetooth communication for file transfer, device control, sensor data exchange, and automation.


1. Setting Up Bluetooth in Python

Python supports Bluetooth communication through libraries like:
pybluez – Classic Bluetooth (SPP, RFCOMM)
bleak – Bluetooth Low Energy (BLE)

Installing Required Libraries

pip install pybluez bleak

2. Discovering Bluetooth Devices

Before connecting, we need to scan for available Bluetooth devices.

Python Code to Scan for Bluetooth Devices (Classic Bluetooth)

import bluetooth

print("Scanning for Bluetooth devices...")
devices = bluetooth.discover_devices(duration=5, lookup_names=True)

for addr, name in devices:
print(f"Found {name} - {addr}")

Finds nearby Bluetooth devices and displays their names & addresses.


3. Connecting to a Bluetooth Device (SPP – Serial Communication)

Some Bluetooth devices, like HC-05, HC-06, or ESP32, use Serial Port Profile (SPP) for communication.

Python Code to Connect & Send Data via Bluetooth (SPP)

import bluetooth

device_address = "XX:XX:XX:XX:XX:XX" # Replace with the target device's Bluetooth address
port = 1 # Commonly used RFCOMM port

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((device_address, port))
print("Connected to Bluetooth device")

sock.send("Hello from Python!")
sock.close()

Establishes Bluetooth communication and sends data.


4. Receiving Data from a Bluetooth Device

Python Code to Receive Data via Bluetooth (SPP)

import bluetooth

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.bind(("", 1))
sock.listen(1)

print("Waiting for connection...")
client, address = sock.accept()
print(f"Connected to {address}")

data = client.recv(1024)
print(f"Received: {data.decode()}")

client.close()
sock.close()

Waits for an incoming Bluetooth connection and receives data.


5. Bluetooth Low Energy (BLE) Communication

BLE is used for low-power IoT devices like smartwatches, heart rate monitors, and temperature sensors.

Scanning for BLE Devices

Python Code to Scan for BLE Devices

import asyncio
from bleak import BleakScanner

async def scan_ble_devices():
devices = await BleakScanner.discover()
for device in devices:
print(device)

asyncio.run(scan_ble_devices())

Finds nearby BLE devices.


Connecting to a BLE Device & Reading Data

Python Code to Connect & Read BLE Data

import asyncio
from bleak import BleakClient

device_address = "XX:XX:XX:XX:XX:XX" # Replace with the BLE device's address
characteristic_uuid = "00002a37-0000-1000-8000-00805f9b34fb" # Example UUID for heart rate data

async def read_ble_data():
async with BleakClient(device_address) as client:
value = await client.read_gatt_char(characteristic_uuid)
print(f"Received data: {value}")

asyncio.run(read_ble_data())

Reads sensor data from a BLE device.


6. File Transfer via Bluetooth (OBEX Protocol)

For sending files over Bluetooth, use obexftp.

Python Code to Send a File via Bluetooth

sudo apt install obexftp  # Install OBEX file transfer tool
import os

device_address = "XX:XX:XX:XX:XX:XX"
file_path = "test.txt"

os.system(f"obexftp --nopath --noconn --uuid none --bluetooth {device_address} --put {file_path}")

Sends a file via Bluetooth.


7. Bluetooth Device Automation Example

Python Code to Automate a Bluetooth Smart Light

import bluetooth

device_address = "XX:XX:XX:XX:XX:XX"
port = 1

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((device_address, port))

# Turn ON the light
sock.send("LIGHT_ON")
sock.close()

Controls a Bluetooth-enabled smart light remotely.

Leave a Reply

Your email address will not be published. Required fields are marked *