扫描&查看MAC:sudo bluetoothctl
输入命令sudo bluetoothctl
进入此工具的命令界面
使用命令scan on
命令可以扫描当前环境中存在的蓝牙设备。
找到需要连接的设备,记录MAC地址。
[NEW] Device 64:46:0B:05:8F:07 64-46-0B-05-8F-07
[CHG] Device 64:46:0B:05:8F:07 LegacyPairing: no
[CHG] Device 64:46:0B:05:8F:07 Name: SU_Band
[CHG] Device 64:46:0B:05:8F:07 Alias: SU_Band
使用bluetoothctl进行连接有些问题。
连接设备:bluez
bluez是linux官方蓝牙协议栈。
安装和配置
#安装
sudo apt-get install pi-bluetooth bluez bluez-firmware blueman
#添加用户到蓝牙组(假设用户名为pi)
sudo usermod -G bluetooth -a pi
sudo reboot #重启
#启动/增加SPP(Serial Port Profile)
sudo vim /etc/systemd/system/dbus-org.bluez.service
给配置文件增加两行:
[Unit]
Description=Bluetooth service
Documentation=man:bluetoothd(8)
ConditionPathIsDirectory=/sys/class/bluetooth
[Service]
Type=dbus
BusName=org.bluez
#增加下面这两行
ExecStart=/usr/lib/bluetooth/bluetoothd -C
ExecStartPost=/usr/bin/sdptool add SP
NotifyAccess=main
#WatchdogSec=10
#Restart=on-failure
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE
LimitNPROC=1
ProtectHome=true
ProtectSystem=full
[Install]
WantedBy=bluetooth.target
Alias=dbus-org.bluez.service
再重启sudo reboot
使用命令hciconfig
查看树莓派的蓝牙信息。
hci0: Type: Primary Bus: UART
BD Address: AA:AA:AA:AA:AA:AA ACL MTU: 1021:8 SCO MTU: 64:1
UP RUNNING PSCAN ISCAN
RX bytes:353313 acl:4941 sco:0 events:9829 errors:0
TX bytes:130290 acl:8889 sco:0 commands:217 errors:0
可以看到设备是hci0
SSP模式与其他蓝牙设备进行连接
从机模式:被动连接
使用命令sudo rfcomm watch hci0
开启等待连接
pi@raspberrypi:~ $ sudo rfcomm watch hci0
Waiting for connection on channel 1
打开手机蓝牙调试助手,连接树莓派蓝牙
连接成功后,/dev/目录下将生成一个设备rfcomm0,可以直接当做串口设备进行使用。
#发送数据
echo 1234541 > /dev/rfcomm0
#读取数据
cat /dev/rfcomm0
主机模式:主动连接
使用命令:sudo rfcomm conn /dev/rfcomm0 [MAC]
连接到目的主机
pi@raspberrypi:~ $ sudo rfcomm conn /dev/rfcomm0 64:46:0B:05:8F:07
Connected /dev/rfcomm0 to 64:46:0B:05:8F:07 on channel 1
Press CTRL-C for hangup
同样,连接成功后可以使用设备rfcomm0进行通讯
#include <sys/types.h> //系统常用类型定义
#include <sys/stat.h> //系统常用文件状态定义
#include <fcntl.h>