Last active
November 14, 2024 11:23
-
-
Save keithweaver/3d5dbf38074cee4250c7d9807510c7c3 to your computer and use it in GitHub Desktop.
Sending information with bluetooth on Raspberry Pi (Python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Uses Bluez for Linux | |
# | |
# sudo apt-get install bluez python-bluez | |
# | |
# Taken from: https://people.csail.mit.edu/albert/bluez-intro/x232.html | |
# Taken from: https://people.csail.mit.edu/albert/bluez-intro/c212.html | |
import bluetooth | |
def receiveMessages(): | |
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) | |
port = 1 | |
server_sock.bind(("",port)) | |
server_sock.listen(1) | |
client_sock,address = server_sock.accept() | |
print "Accepted connection from " + str(address) | |
data = client_sock.recv(1024) | |
print "received [%s]" % data | |
client_sock.close() | |
server_sock.close() | |
def sendMessageTo(targetBluetoothMacAddress): | |
port = 1 | |
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) | |
sock.connect((targetBluetoothMacAddress, port)) | |
sock.send("hello!!") | |
sock.close() | |
def lookUpNearbyBluetoothDevices(): | |
nearby_devices = bluetooth.discover_devices() | |
for bdaddr in nearby_devices: | |
print str(bluetooth.lookup_name( bdaddr )) + " [" + str(bdaddr) + "]" | |
lookUpNearbyBluetoothDevices() |
I got an issue with this program:
Detecting bluetooth devices works just fine, I can detect my phone and my other bluetooth devices, but when sending messages to my phone a "connection refused" error raises (but that's probably because it's got some built-in protection against scary Linux devices). So that's when I thought 'hey, what if I try it using my pi zero w?'
so I used two pi's for my tryout of this program:
- a headless pi zero w automatically loads the script (using crontab), detects bluetooth devices using lookUpNearbyBluetoothDevices() and sends a message to all of them (by using sendMessageTo in a try function)
- a pi 4 B connected to a monitor is running the function receiveMessages(), but doesn't receive anything at all
And that's the problem! They're both pi's , and I suppose sending messages between two pi's using this program would work.
Can anyone help me out please?
PS: I like your program, even when only a small part of it works that's a lot better than most internet pieces of code.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What guinea pigs? Are you torturing some pigs?