蓝牙通信代码示例分享
以下是一份蓝牙通信代码示例,供大家参考和学习:
import bluetooth
# 扫描附近蓝牙设备
nearby_devices = bluetooth.discover_devices()
# 连接蓝牙设备
for device_address in nearby_devices:
device_name = bluetooth.lookup_name(device_address)
if "手机" in device_name: # 仅以手机为例
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
try:
sock.connect((device_address, 1))
print("成功连接到手机:", device_name)
# 发送数据
sock.send("Hello, Bluetooth!")
print("已发送数据:Hello, Bluetooth!")
# 接收数据
data = sock.recv(1024)
print("接收到的数据:", data.decode())
except bluetooth.BluetoothError as e:
print("连接失败:", e)
sock.close()