MarkDown
# PyBLE: Playing with Bluetooth Low Energy Communication using Python
Hello everyone! Today we are going to explore a super cool Python library - PyBLE. This library is specifically designed for Bluetooth Low Energy (BLE) communication, allowing us to easily connect and control various smart devices such as fitness bands, smart bulbs, sensors, and more using Python. Even if you are a Python beginner, you can quickly get started with BLE development by following this article step by step!
## 1. What is Bluetooth Low Energy (BLE)
Bluetooth Low Energy (BLE) is a technology introduced with Bluetooth 4.0, characterized by low power consumption and fast connections. Most of the Bluetooth functionality on our smartphones, smartwatches, and health monitoring devices utilize BLE technology.
The PyBLE library is a Python wrapper for the system's BLE interface, enabling BLE communication without the need to learn complex low-level protocols. It supports:
- Scanning for nearby BLE devices
- Connecting to devices and discovering services
- Reading and writing device data
- Receiving notifications from devices
```python
# First, install the PyBLE library
# pip install pyble
2. Scanning for Nearby BLE Devices
The first step in using PyBLE is to discover nearby BLE devices. It’s as simple as searching for nearby devices with your phone’s Bluetooth.
from pyble import Scanner
scanner = Scanner()
devices = scanner.scan(timeout=5) # Scan for 5 seconds
for device in devices:
print(f"Discovered device: {device.name}, MAC address: {device.address}, Signal strength: {device.rssi}dBm")
Tip: You may see many unnamed devices during the scan because many BLE devices do not broadcast their names by default. A higher signal strength (rssi) value indicates a better signal (closer to 0 means a stronger signal).
3. Connecting to a BLE Device
After finding the target device, we can establish a connection. The MAC address of the device is required for the connection.
from pyble import Central
central = Central()
device = central.connect("AA:BB:CC:DD:EE:FF") # Replace with the target device address
if device.is_connected:
print("Connection successful!")
else:
print("Connection failed")
Notes:
-
Ensure the device is not occupied by other programs before connecting
-
Some devices require a pairing code, and a prompt will appear during connection
-
The default connection timeout is 10 seconds, which can be adjusted using the timeout parameter
4. Discovering Device Services and Characteristics
BLE devices organize their functionalities through “Services” and “Characteristics”. For example, a smart band may have:
-
Battery service: Read battery level
-
Heart rate service: Get heart rate data
-
Device information service: Read firmware version
Python
services = device.discover_services()
for service in services:
print(f"Service UUID: {service.uuid}")
characteristics = service.discover_characteristics()
for char in characteristics:
print(f" Characteristic UUID: {char.uuid}, Readable: {char.can_read}, Writable: {char.can_write}")
5. Reading and Writing Data
After discovering characteristics, we can read data or send commands. For example, to read the device name:
# Read device name (usually found in the device information service)
device_info_service = device.get_service("0000180a-0000-1000-8000-00805f9b34fb")
manufacturer_name_char = device_info_service.get_characteristic("00002a29-0000-1000-8000-00805f9b34fb")
name = manufacturer_name_char.read()
print(f"Device name: {name.decode('utf-8')}")
Writing data is also straightforward, for example, to control a smart bulb:
light_service = device.get_service("00001802-0000-1000-8000-00805f9b34fb")
switch_char = light_service.get_characteristic("00002a06-0000-1000-8000-00805f9b34fb")
# Turn on the light (send 1)
switch_char.write(b'\x01')
6. Receiving Notifications
Some devices actively push data (like heart rate monitoring), and we need to set up notification callbacks:
def on_heart_rate_changed(value):
print(f"Current heart rate: {value[0]} beats/minute")
heart_service = device.get_service("0000180d-0000-1000-8000-00805f9b34fb")
heart_char = heart_service.get_characteristic("00002a37-0000-1000-8000-00805f9b34fb")
heart_char.start_notify(on_heart_rate_changed)
Important Reminder: Remember to stop notifications and disconnect before exiting the program!
heart_char.stop_notify()
device.disconnect()
Conclusion
Today we learned the basic usage of the PyBLE library:
-
Use Scanner to scan for BLE devices
-
Connect to the target device using Central
-
Discover the services and characteristics of the device
-
Read and write characteristic data
-
Receive notifications from the device
Hands-on Practice: Try connecting to a real BLE device (like a fitness band) and read its battery information or device name.
Friends, this concludes our Python learning journey for today! Remember to write code, and feel free to ask questions in the comments. Happy learning, and may your Python skills improve steadily!
Previous Reviews
◆
◆
◆
Like and Share
Letmoney and love flow to you