我正在尝试在运行 Raspbian Jessie [03-07-2017]的Raspberry Pi Zero W和Arduino(UNO)之间 Build 蓝牙串行通信链路 . 我目前能够使用 bluetoothctl 将数据写入Arduino .

该应用程序要求我们能够将数据写入特定的BLE从站 . 有多个[HM-10]从器件之间需要切换,需要在程序执行期间选择从器件 .

没有BAUD费率偏好 . 目前,我们普遍使用9600 .

已创建的函数可自动连接然后将数据写入“属性”,这将显示为Arduino串行监视器上的数据 .

Python代码 - 使用 BlueZ 5.44 (手动安装):

import subprocess
from subprocess import Popen, PIPE

# Replaces the ':' with '_' to allow the MacAddress to be in the form
# of a "Path" when "selecting an attribute"
def changeMacAddr(word):
    return ''.join(c if c != ':' else '_' for c in word)

# Connects to a given MacAddress and then selects the attribute to write to
def connBT(BTsubProcess, stringMacAddr):
    BTsubProcess.stdin.write(bytes("".join("connect "+stringMacAddr +"\n"), "utf-8"))
    BTsubProcess.stdin.flush()
    time.sleep(2)
    stringFormat = changeMacAddr(stringMacAddr)
    BTsubProcess.stdin.write(bytes("".join("select-attribute /org/bluez/hci0/dev_"
                              + stringFormat +
                              "/service0010/char0011" + "\n"), "utf-8"))
    BTsubProcess.stdin.flush()

# Can only be run once connBT has run - writes the data in a list [must have numbers 0 - 255 ]
def writeBT(BTsubProcess, listOfData):
    stringList = [str('{0} ').format(elem) for elem in listOfData]
    BTsubProcess.stdin.write(bytes("".join("write " + "".join(stringList) + "\n"), "utf-8"))
    BTsubProcess.stdin.flush()

# Disconnects
def clostBT(BTsubProcess):
    BTsubProcess.communicate(bytes("disconnect\n", "utf-8"))

# To use the functions a subprocess "instance" of bluetoothctl must be made
blt = subprocess.Popen(["bluetoothctl"], stdin=subprocess.PIPE, shell=True)
# blt with then be passed into the function for BTsubProcess

# Note: the MacAddresses of the Bluetooth modules were pre-connected and trusted manually via bluetoothctl

这种方法适用于小型数据集,但我的要求要求我非常快速地将数据流式传输到Arduino .

目前的设置是:

  • Pi接收通过USB串行传感器数据(加速度计,EEG)

  • Pi处理数据

  • 然后通过Pi Zero W的内置蓝牙将命令发送到Arduino

然而,在使用该方法时,当传感器数据改变时,蓝牙数据传输将延迟(暂时冻结) .


使用两个预先配对的HM-10模块时,数据传输完美无缺,Pi的GPIO串口使用 PySerial 进行配置 .

还尝试了以下方法:

  • 使用 WiringPi 在/ dev / ttyAMA0上设置蓝牙串口

  • 使用Python套接字和 rfcomm

尝试使用这两种方法时 . 然而,Python代码编译后,一旦打开串行端口,数据似乎没有被写入,并且没有显示在Arduino的串行监视器上 .

这会削弱以前的功能 . 即使手动使用 bluetoothctl ,模块也不能取消配对/断开连接 . 写入适当的属性也不起作用 .

需要重新启动才能恢复正常功能 .


这种方法是否正确?有没有更好的方式通过BLE发送数据?


UPDATE: 05/07/2017
我不再从事这个项目了 . 但故障排除让我相信代码中的"race condition"可能导致程序无法正常运行 .
这在测试阶段得到了验证,在这个阶段创建了一个功能非常好的准系统代码 .