bluetooth

桌面系统配置蓝牙

文档编写中,敬请期待

命令行配置蓝牙

使用命令行配置蓝牙,我们需要使用工具—-bluetoothctl

# 进入bluetoothctl命令行
bluetoothctl
# 进入bluetoothctl命令行后,类似:[bluetooth]#
# Controller代表arm板上的蓝牙设备,Device代表蓝牙耳机
# 按如下步骤初始化蓝牙设备,并连接蓝牙耳机
# 查看帮组
help

power on
agent on
default-agent
# 启动扫描
scan on
# 假如蓝牙耳机地址为:04:8C:9A:F2:54:4B
trust 04:8C:9A:F2:54:4B
# 配对
pair 04:8C:9A:F2:54:4B
# 连接
connect 04:8C:9A:F2:54:4B

# 查看蓝牙耳机信息
info 04:8C:9A:F2:54:4B

# 断开连接
disconnect 04:8C:9A:F2:54:4B
# 不想自动连接上蓝牙耳机,可以删除配对信息
remove 04:8C:9A:F2:54:4B

更多关于命令行蓝牙连接,可参考 https://blog.csdn.net/chenjk10/article/details/90317028

蓝牙串行通信

首先安装相关工具

sudo apt update
sudo apt install bluez util-linux
sudo apt install bluez bluez-tools bluez-firmware

查看蓝牙信息

#执行命令
hciconfig -a

#打印信息如下
hci0:   Type: Primary  Bus: USB
     BD Address: 2C:C3:E6:63:42:57  ACL MTU: 1021:8  SCO MTU: 255:12
     UP RUNNING PSCAN
     RX bytes:4845 acl:0 sco:0 events:434 errors:0
     TX bytes:55369 acl:0 sco:0 commands:434 errors:0
     Features: 0xff 0xff 0xff 0xfe 0xdb 0xfd 0x7b 0x87
     Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
     Link policy: RSWITCH HOLD SNIFF PARK
     Link mode: SLAVE ACCEPT
     Name: 'lubancat'
     Class: 0x3c0000
     Service Classes: Rendering, Capturing, Object Transfer, Audio
     Device Class: Miscellaneous,
     HCI Version: 4.2 (0x8)  Revision: 0x75b8
     LMP Version: 4.2 (0x8)  Subversion: 0xf098
     Manufacturer: Realtek Semiconductor Corporation (93)

修改配置文件

修改配置文件/etc/systemd/system/dbus-org.bluez.service

sudo vim /etc/systemd/system/dbus-org.bluez.service

修改如下,/usr/libexec/bluetooth/bluetoothd这个路径不同系统可能会不一样,按原本的路径即可

ExecStart=/usr/libexec/bluetooth/bluetoothd -C
ExecStartPost=/usr/bin/sdptool add SP

重启蓝牙服务

sudo systemctl daemon-reload
sudo /etc/init.d/bluetooth restart

取消确认蓝牙pin码(非必须)

新建/usr/lib/systemd/system/bt-agent.service 写入以下内容

[Unit]
Description=Bluetooth Auth Agent

[Service]
Type=simple
ExecStartPre=/bin/sleep 15
ExecStart=/usr/bin/bt-agent -c NoInputNoOutput
User=root

[Install]
WantedBy=bluetooth.target

启动服务,重启系统

sudo systemctl start bt-agent
sudo systemctl enable bt-agent
reboot

配置蓝牙可以被发现

sudo hciconfig hci0 piscan

连接蓝牙设备

sudo rfcomm watch hci0 &

在前面使用 hciconfig -a 命令可以看到蓝牙的名字叫xniupi,地址是2C:C3:E6:63:42:57(不同蓝牙会不一样)。我们打开手机上的蓝牙软件,比如笔者使用的是——蓝牙调试宝,一般在手机应用商店可以下载

打开软件,可以搜索到蓝牙设备,然后进行连接,连接成功,终端会打印提示信息:

Connection from A8:C5:6F:0D:ED:AE to /dev/rfcomm0
Press CTRL-C for hangup

此时/dev目录下也有一个rfcomm0设备,可以通过下面命令查看:

#执行命令
ls /dev/rfcomm0

我们可以通过下面命令发送一些数据到手机的蓝牙调试工具上:

echo "6666666" > /dev/rfcomm0

可以看到手机的蓝牙调试工具上已经收到了相关的数据,

当然手机也可以发送数据到开发板上,比如我们发送一些ASCII码字符串到开发板上, 然后在终端通过cat命令去读取这些数据,可以看到通信是正常的:

 #执行命令
cat /dev/rfcomm0

#打印信息
12
111
6666