-
首先找到指定设备名的蓝牙设备,得到设备地址
-
根据地址连接设备(前提是PC端先配对好)
-
发送数据
代码如下:
import bluetooth
# 扫描经典蓝牙设备
def scan_devices():
devices = bluetooth.discover_devices(lookup_names=True)
print("Found devices:")
return devices
# 配对设备(需系统支持)
def pair_device(address):
# Windows 下 PyBluez 无法直接配对,需调用系统功能
import subprocess
subprocess.run(["btpair", "-p", address]) # 模拟命令行配对(非实际代码)
# 通过 RFCOMM 连接并发送数据
def send_data(address, port=1):
print("连接:"+address)
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((address, port))
sock.send("Hello from PC!")
response = sock.recv(1024)
print(f"Received: {response}")
sock.close()
if __name__ == "__main__":
target_name = "ESP32-liuyan"
target_address = ""
devices = scan_devices()
for addr, name in devices:
print(f" {name} - {addr}")
if name == target_name:
print("找到目标设备")
target_address = addr
break
if target_address == "":
print("找不到目标设备")
else:
# 手动输入目标设备地址
# target_address = "00:11:22:33:44:55"
#pair_device(target_address) # 需配合Windows API
# send_data(target_address)
print("连接:"+target_address)
try:
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.settimeout(10) # 设置超时10秒
print("尝试连接...")
sock.connect((target_address, 1))
print("连接成功!")
# 发送数据示例
num = 0
while num < 100000:
sock.send("Hello Bluetooth!\n")
num = num +1
sock.close()
except bluetooth.btcommon.BluetoothError as e:
print(f"连接失败: {e}")
except Exception as e:
print(f"其他错误: {e}")
|
运行环境是什么样的?