Reputation: 21
I'm working for some school project. I want to send temperature sensor data from one raspberry pi 4 to another pi 4 via Bluetooth. I searched a lot for tutorial but I didn't find any related tutorial. Please anyone help with this or any suggestions would be very helpful.
Upvotes: 1
Views: 5191
Reputation: 207798
I know very little about Bluetooth and this answer may be dated or poor practice, but at least it works. If anyone knows better, please provide a better answer and I will delete this.
So, I have two Raspberry Pi 4 running Raspbian. I installed BlueDot
on both with:
sudo pip3 install bluedot
I then paired them, running this on the first:
sudo bluetoothctl
[bluetooth]# discoverable on
[bluetooth]# pairable on
[bluetooth]# agent on
[bluetooth]# default-agent
and this on the second:
sudo bluetoothctl
[bluetooth]# discoverable on
[bluetooth]# pairable on
[bluetooth]# agent on
[bluetooth]# default-agent
[bluetooth]# scan on
When the first RasPi (hostname=pi4) showed up, I paired with it by typing this in the second RasPi:
[bluetooth]# pair DC:A6:32:03:0C:1B
Then I quit bluetoothctl
on both.
Then I ran this server code (attributable to here) on the first RasPi UNDER 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")
And this code (attributable to here) on the second, also under 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()
The two RasPis swapped messages successfully till interrupted. I measured the Round Trip Time (RTT) and it averaged around 30ms between two RasPi 4 placed around a metre apart.
It may be better to add the pi
user to the dialout
Linux group (or some other one) rather than run under sudo
. If anyone knows, please say.
Upvotes: 5