ESP32平台MicroPython aioble库使用及调试问题求助
ESP32 MicroPython aioble BLE连接问题排查与修复
代码中的核心问题
- 设备扫描逻辑错误:
main函数中,首次扫描不到设备进入循环后直接执行return退出程序,导致无法重试扫描。 - 变量作用域冲突:全局变量
mtu_connect在main内被重新定义为局部变量,导致连接失败后无法正确累加重试次数。 - 服务UUID不匹配:你使用的
00001800-0000-1000-8000-00805F9B34FB是BLE通用访问服务(GAP)UUID,而非温度传感器对应的环境传感服务(标准UUID为0000180F-0000-1000-8000-00805F9B34FB),若目标设备用自定义UUID需替换为对应值。 - 重试逻辑不完善:连接失败后未清理残留连接对象,可能影响下一次重试。
修正后的代码
import sys sys.path.append("") from micropython import const import uasyncio as asyncio import aioble import bluetooth # 替换为温度传感器实际使用的服务UUID,示例为标准环境传感服务 SERVICE_UUID = bluetooth.UUID('0000180F-0000-1000-8000-00805F9B34FB') async def find_temp_sensor(): # 主动模式扫描10秒,参数平衡检测效率与功耗 async with aioble.scan(10000, interval_us=12000, window_us=10000, active=True) as scanner: async for result in scanner: print(result, result.name(), result.rssi, result.services()) if result.name() == "70001697": return result.device return None async def main(): device = await find_temp_sensor() # 循环扫描直到找到目标设备 while not device: print("Temperature sensor not found, retrying...") await asyncio.sleep(2) # 增加扫描间隔,避免频繁扫描 device = await find_temp_sensor() print(f"Found device: {device}") retry_count = 0 connection = None while retry_count < 3: try: print(f"Connecting to {device} (attempt {retry_count + 1})") # 设置连接超时,避免无限等待 connection = await device.connect(timeout=5000) print("Connected successfully") service = await connection.service(SERVICE_UUID) print(f"Found service: {service.uuid}") # 枚举并打印特征UUID char_uuids = [] async for char in service.characteristics(): char_uuids.append(str(char.uuid)) print("Discovered characteristics:", sorted(char_uuids)) print("Connection setup completed!") break except asyncio.TimeoutError: print("Connection timeout") retry_count += 1 # 清理残留连接 if connection: await connection.disconnect() except Exception as e: print(f"Connection failed: {str(e)}") retry_count += 1 if connection: await connection.disconnect() else: print("Failed to connect after 3 attempts") asyncio.run(main())
额外说明
- 先用BLE调试工具(如nRF Connect)确认目标设备的服务UUID,确保与代码中设置一致。
- 扫描间隔、窗口参数可根据实际环境调整,缩短窗口会提升检测频率但增加功耗。
- 新增的通用异常捕获能帮助排查更多连接失败原因,比如设备拒绝连接、信号弱等。
内容的提问来源于stack exchange,提问作者Nguyễn Thuận Hải
相关产品推荐
相关产品推荐

