一、树莓派中的蓝牙
Raspberry中已经安装了Bluez。我使用的版本是5.50。你可以通过以下命令检查自己的BlueZ版本:
bluetoothd -v
可以用下面的命令检查Bluez的运行状态:
systemctl status bluetooth
可以看到我的返回结果显示蓝牙已经打开并正在运行。
你可以用下面命令手动启动或关闭蓝牙服务:
sudo systemctl start bluetooth
sudo systemctl stop bluetooth
此外,你还可以让蓝牙服务随系统启动:
sudo systemctl enable bluetooth
在Raspberry中,基本的蓝牙操作可以通过bluez中的bluetoothctl命令进行。该命令运行后,将进入到一个新的Shell。在这个shell中输入:
list
将显示树莓派上可用的蓝牙模块,例如:
运行scan命令,开启扫描:
scan on
虽然树莓派中已经有了蓝牙,但是还是建议执行一下以下命令,以方便蓝牙的使用:
一、升级安装蓝牙相关软件包
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get dist-upgrade -y
sudo apt-get install pi-bluetooth bluez bluez-firmware blueman
二、最关键一点:添加pi用户到蓝牙组
sudo usermod -G bluetooth -a pi
三、重启
sudo reboot
执行完毕之后你就会发现树莓派上面状态栏多了一个蓝牙的图标,方便使用蓝牙。
二、通过python使用树莓派蓝牙
python中有蓝牙对应的库可以使用,比如:bluetooth库。这个库对应的是pybluez蓝牙。
通过蓝牙名称来查找蓝牙:
import bluetooth
target_name = "Device Name"
target_address = None
nearby_devices = bluetooth.discover_devices()
for bdaddr in nearby_devices:
if target_name == bluetooth.lookup_name( bdaddr ):
target_address = bdaddr
break
if target_address is not None:
print("found target bluetooth device with address ", target_address)
else:
print("could not find target bluetooth device nearby")
运行如上代码可能会发生如下报错:
ModuleNotFoundError: No module named ‘bluetooth’
原因可能是你安装bluez库时是使用python 2版本下载的,python 2版本不支持bluez。
解决方法:用python 3版本下载bluez。
python3 -m pip install pybluez
三、通过蓝牙进行通信
可采用类似于socket编程模型的方式进行蓝牙通信的编程,主要有两种协议:RFCOMM协议和L2CAP协议。
用这两种协议的用法没什么太大的区别,除了端口以外其他都差不多。
网上有些教程说RFCOMM支持的端口范围为1~30号端口,L2CAP端口是0x1001到0x8FFF之间的奇数端口。但是我使用L2CAP协议时,端口分别设置为0x1001到0x1009都无法成功通讯,设置为0x100b以及后面的奇数端口才成功连接通信,我不知道是L2CAP支持的端口不是从0x1001开始的问题还是我树莓派对应的端口已经被占用了的问题。使用命令 netstat -nultp 查看已经使用的端口发现上述端口并未被占用,所以我也搞不懂了,你们也可以自己测试一下哪些端口可以成功