0
0
Drone-programmingHow-ToBeginner · 3 min read

How to Scan BLE Devices: Simple Steps and Example Code

To scan BLE devices, use a BLE scanning tool or library that listens for nearby BLE advertisements. For example, on Linux, the bluetoothctl scan on command starts scanning, while in code, libraries like bluepy or bleak can scan and list devices.
📐

Syntax

BLE scanning involves starting a scan process that listens for advertising packets from nearby BLE devices. The basic syntax depends on the tool or library used.

  • bluetoothctl (Linux CLI): scan on starts scanning, scan off stops it.
  • Python bleak library: Use BleakScanner to start scanning asynchronously.
bash
bluetoothctl scan on
Output
Discovery started [NEW] Device XX:XX:XX:XX:XX:XX Device_Name
💻

Example

This Python example uses the bleak library to scan for BLE devices for 5 seconds and print their addresses and names.

python
import asyncio
from bleak import BleakScanner

async def scan_ble():
    devices = await BleakScanner.discover(timeout=5.0)
    for d in devices:
        print(f"Device: {d.address}, Name: {d.name}")

asyncio.run(scan_ble())
Output
Device: AA:BB:CC:DD:EE:FF, Name: BLE_Device_1 Device: 11:22:33:44:55:66, Name: BLE_Device_2
⚠️

Common Pitfalls

Common mistakes when scanning BLE devices include:

  • Not having Bluetooth enabled or permissions granted on the device.
  • Not stopping previous scans before starting a new one, causing conflicts.
  • Ignoring asynchronous behavior in code, leading to missed devices.
  • Using outdated libraries or commands that no longer work with modern BLE stacks.
bash
## Wrong: Starting scan without stopping previous one (bluetoothctl)
bluetoothctl scan on
bluetoothctl scan on

## Right: Stop before starting new scan
bluetoothctl scan off
bluetoothctl scan on
📊

Quick Reference

Command/FunctionDescription
bluetoothctl scan onStart scanning for BLE devices on Linux CLI
bluetoothctl scan offStop scanning
BleakScanner.discover(timeout)Scan for BLE devices in Python asynchronously
Ensure Bluetooth enabledBluetooth adapter must be on and ready
Run with permissionsScan requires proper OS permissions

Key Takeaways

Use bluetoothctl scan on on Linux to start BLE scanning quickly.
In Python, use the bleak library's BleakScanner.discover() for asynchronous scanning.
Always ensure Bluetooth is enabled and you have necessary permissions before scanning.
Stop any ongoing scans before starting a new one to avoid conflicts.
BLE scanning listens for advertising packets from nearby devices to discover them.