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

树莓派与需PIN码的BLE设备配对连接异常问题求助

解决方案:树莓派与需PIN码的BLE设备稳定配对

1. 正确配置蓝牙配对流程(解决无PIN提示+自动断开问题)

进入bluetoothctl交互模式,手动处理配对与信任逻辑,确保设备完成bonding:

sudo bluetoothctl
# 开启配对代理
agent on
default-agent
# 扫描设备(找到目标MAC后停止)
scan on
scan off
# 若配对时无PIN提示,切换到键盘显示模式触发输入
set-agent KeyboardDisplay
# 执行配对,此时按提示输入设备的初始PIN码(即配套APP首次使用的PIN)
pair <设备MAC地址>
# 信任设备,允许自动重连
trust <设备MAC地址>
# 主动发起连接
connect <设备MAC地址>

完成后退出交互模式,设备会保存bonding信息,后续无需重复输入PIN。

2. 关闭蓝牙节能与优化配置

树莓派默认蓝牙节能机制可能导致闲置断开,修改配置文件:

sudo nano /etc/bluetooth/main.conf

调整以下参数:

AutoEnable=true
ControllerMode = bredr
DisablePlugins = pnat

重启蓝牙服务生效:

sudo systemctl restart bluetooth

3. 用bluepy实现带PIN的配对与持久连接

bluepy默认未处理PIN验证,需手动添加配对回调:

from bluepy.btle import Peripheral, DefaultDelegate, BTLEException
import time

class PairingDelegate(DefaultDelegate):
    def handlePairingRequest(self, conn):
        # 替换为你的设备PIN码
        conn.setPin("1234")
        return True

try:
    # 若设备用随机蓝牙地址,需添加"random"参数
    dev = Peripheral("<设备MAC地址>", "random")
    dev.setDelegate(PairingDelegate())
    # 触发配对
    dev.pair(None)
    # 保持连接:定期与设备交互(示例为读取特征值,替换为你的设备特征UUID)
    while True:
        target_char = dev.getCharacteristics(uuid="0000ffe1-0000-1000-8000-00805f9b34fb")[0]
        print("设备数据:", target_char.read())
        time.sleep(3)
except BTLEException as e:
    print("连接异常:", e)
finally:
    dev.disconnect()

先更新bluepy到最新版本:

sudo pip3 install bluepy --upgrade

4. 验证Bonding状态

检查树莓派是否已保存设备的bonding信息:

ls /var/lib/bluetooth/<树莓派蓝牙控制器MAC>/

若存在对应设备MAC的文件夹,说明bonding成功;若不存在,重新执行配对+信任流程。

内容的提问来源于stack exchange,提问作者Nguyen Cao Hoang Nam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:25:19