0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Send Data Over Bluetooth on Raspberry Pi Easily

To send data over Bluetooth on a Raspberry Pi, you can use the bluetooth Python library or system tools like bluetoothctl and rfcomm. First, pair your Raspberry Pi with the target device, then create a Bluetooth socket in Python to send data using socket.send().
📐

Syntax

Here is the basic syntax to send data over Bluetooth using Python's bluetooth library:

  • import bluetooth: Import the Bluetooth module.
  • sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM): Create a Bluetooth socket using RFCOMM protocol.
  • sock.connect((address, port)): Connect to the device's Bluetooth address and port.
  • sock.send(data): Send data as bytes or string.
  • sock.close(): Close the socket after sending.
python
import bluetooth

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect(('XX:XX:XX:XX:XX:XX', 1))  # Replace with device address and port
sock.send('Hello Raspberry Pi')
sock.close()
💻

Example

This example shows how to send a simple text message from Raspberry Pi to a paired Bluetooth device using Python.

python
import bluetooth

# Replace with your device's Bluetooth MAC address
target_address = '01:23:45:67:89:AB'
port = 1

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((target_address, port))
sock.send('Hello from Raspberry Pi!')
sock.close()
⚠️

Common Pitfalls

Common mistakes when sending data over Bluetooth on Raspberry Pi include:

  • Not pairing devices before connecting, causing connection failures.
  • Using the wrong Bluetooth address or port number.
  • Forgetting to close the socket, which can block future connections.
  • Not running the script with proper permissions (try sudo if needed).

Always ensure your Raspberry Pi's Bluetooth is enabled and the target device is discoverable or already paired.

python
import bluetooth

# Wrong way: Not pairing or wrong address
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect(('00:00:00:00:00:00', 1))  # Invalid address
sock.send('Test')
sock.close()

# Right way:
# 1. Pair devices using bluetoothctl
# 2. Use correct address
# 3. Run script with sudo if permission denied
📊

Quick Reference

Tips for sending data over Bluetooth on Raspberry Pi:

  • Use bluetoothctl to scan, pair, and trust devices.
  • Use RFCOMM protocol for serial communication.
  • Always close sockets after use.
  • Run Python scripts with sudo if you face permission errors.
  • Check Bluetooth status with hciconfig.

Key Takeaways

Pair your Raspberry Pi with the target Bluetooth device before sending data.
Use Python's bluetooth library with RFCOMM sockets to send data easily.
Always use the correct Bluetooth address and port number.
Close the Bluetooth socket after sending data to free resources.
Run scripts with sudo if you encounter permission issues.