You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP32上用MicroPython扫描UART服务设备报AttributeError求助

解决MicroPython ESP32 BLE扫描的AttributeError问题

错误原因

你的代码核心问题是对ubluetooth.BLE.gap_scan()的用法误解:该方法不返回扫描器实例,执行后直接启动扫描流程,因此scanner变量被赋值为None,后续调用scanner.scan()就会触发AttributeError: 'NoneType' object has no attribute 'scan'。

修正后的实现代码

MicroPython的BLE扫描需要通过回调函数处理扫描结果,以下是正确的实现逻辑:

import ubluetooth

# 定义Nordic UART服务UUID(标准值)
UART_SERVICE_UUID = ubluetooth.UUID("6E400000-B5A3-F393-E0A9-E50E24DCCA9E")

ble = ubluetooth.BLE()
ble.active(True)

# 存储扫描到的目标设备
target_device = None

def scan_callback(event, data):
    global target_device
    if event == ubluetooth.EVT_GAP_SCAN_RESULT:
        addr_type, addr, adv_type, rssi, adv_data = data
        # 解析广播数据中的服务UUID
        try:
            # 提取服务UUID列表
            services = ble.decode_adv_data(adv_data, ubluetooth.ADV_DATA_UUID128_COMPLETE)
            if UART_SERVICE_UUID in services:
                # 获取设备名称
                name = ble.decode_adv_data(adv_data, ubluetooth.ADV_DATA_NAME_COMPLETE) or ble.decode_adv_data(adv_data, ubluetooth.ADV_DATA_NAME_SHORT)
                print(f"找到UART设备: {name or addr}")
                target_device = (addr_type, addr)
                # 停止扫描
                ble.gap_scan(None)
        except ValueError:
            pass

# 启动扫描:扫描时长10秒,间隔30ms,窗口30ms
ble.gap_scan(10000, 30000, 30000, False, scan_callback)

# 等待扫描结束或找到目标设备
while target_device is None:
    pass

# 连接目标设备
print("正在连接设备...")
conn_handle = ble.connect(target_device[0], target_device[1])

# 等待连接建立
while True:
    events = ble.gap_events()
    if events & ubluetooth.EVT_GAP_CONNECTED:
        print("连接成功!")
        break
    elif events & ubluetooth.EVT_GAP_DISCONNECTED:
        print("连接失败,重试...")
        conn_handle = ble.connect(target_device[0], target_device[1])

关键说明

  • 使用ble.gap_scan()时传入回调函数,通过EVT_GAP_SCAN_RESULT事件获取扫描到的设备数据
  • 用ble.decode_adv_data()解析广播中的服务UUID和设备名称
  • 找到目标设备后调用ble.gap_scan(None)停止扫描
  • 通过ble.gap_events()监听连接状态事件

内容的提问来源于stack exchange,提问作者Miracle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:03:01