如何通过蓝牙在两个树莓派之间进行通信并将传感器数据从一个树莓派发送到另一个树莓派?

Gan*_*esh 1 python bluetooth raspberry-pi

我正在为一些学校项目工作。我想通过蓝牙将温度传感器数据从一个树莓派 4 发送到另一台树莓派 4。我搜索了很多教程,但没有找到任何相关的教程。请任何人帮忙解决这个问题,或者任何建议都会非常有帮助。

Mar*_*ell 5

我对蓝牙知之甚少,这个答案可能已经过时或实践不佳,但至少它有效。如果有人知道更好,请提供更好的答案,我会删除它。

所以,我有两个运行 Raspbian 的 Raspberry Pi 4。我BlueDot在两者上都安装了:

sudo pip3 install bluedot
Run Code Online (Sandbox Code Playgroud)

然后我将它们配对,在第一个上运行:

sudo bluetoothctl
[bluetooth]# discoverable on
[bluetooth]# pairable on
[bluetooth]# agent on
[bluetooth]# default-agent
Run Code Online (Sandbox Code Playgroud)

这是第二个:

sudo bluetoothctl
[bluetooth]# discoverable on
[bluetooth]# pairable on
[bluetooth]# agent on
[bluetooth]# default-agent
[bluetooth]# scan on
Run Code Online (Sandbox Code Playgroud)

当第一个 RasPi(主机名=pi4)出现时,我通过在第二个 RasPi 中输入以下内容来与它配对:

[bluetooth]# pair DC:A6:32:03:0C:1B
Run Code Online (Sandbox Code Playgroud)

然后我就放弃了bluetoothctl这两件事。

然后我在第一个 RasPi 上运行此服务器代码(归因于此处) :sudo

#!/usr/bin/env python3

from bluedot.btcomm import BluetoothServer
from time import sleep
from signal import pause

def data_received(data):
    print("recv - {}".format(data))
    server.send(data)

def client_connected():
    print("client connected")

def client_disconnected():
    print("client disconnected")

print("init")
server = BluetoothServer(
    data_received,
    auto_start = False,
    when_client_connects = client_connected,
    when_client_disconnects = client_disconnected)

print("starting")
server.start()
print(server.server_address)
print("waiting for connection")

try:
    pause()
except KeyboardInterrupt as e:
    print("cancelled by user")
finally:
    print("stopping")
    server.stop()
print("stopped")
Run Code Online (Sandbox Code Playgroud)

这段代码(归因于此处)位于第二个,也在下面sudo

#!/usr/bin/env python3

from bluedot.btcomm import BluetoothClient
from datetime import datetime
from time import sleep
from signal import pause

def data_received(data):
    print("recv - {}".format(data))

print("Connecting")
c = BluetoothClient("pi4", data_received)

print("Sending")
try:
    while True:
        c.send("hi {} \n".format(str(datetime.now())))
        sleep(1)
finally:
    c.disconnect()
Run Code Online (Sandbox Code Playgroud)

两个RasPi成功交换消息直至中断。我测量了往返时间 (RTT),两个相距一米左右的 RasPi 4 之间的平均往返时间约为 30 毫秒。

pi将用户添加到dialoutLinux 组(或其他组)可能比在sudo. 如果有人知道请说一下。