蓝牙通信代码示例分享

qqdefy26875 15 0 zip 2023-07-02 17:07:40

以下是一份蓝牙通信代码示例,供大家参考和学习:

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()

用户评论
请输入评论内容
评分:
暂无评论