从机模式:例如微信小程序上蓝牙搜索树莓派蓝牙服务,配对连接。然后访问树莓派蓝牙提供的服务。
一、安装python库
pip3 install dbus-python
pip3 install bluezero
二、例子代码一(cpu_temperature.py)
import logging
import random
from bluezero import async_tools, adapter, peripheral
CPU_TMP_SRVC = '12341000-1234-1234-1234-123456789abc'
# https://www.bluetooth.com/specifications/assigned-numbers/
# Bluetooth SIG adopted UUID for Temperature characteristic
CPU_TMP_CHRC = '2A6E'
# Bluetooth SIG adopted UUID for Characteristic Presentation Format
CPU_FMT_DSCP = '2904'
def read_value():
cpu_value = random.randrange(3200, 5310, 10) / 100
return list(int(cpu_value * 100).to_bytes(2, byteorder='little', signed=True))
def update_value(characteristic):
new_value = read_value()
characteristic.set_value(new_value)
return characteristic.is_notifying
def notify_callback(notifying, characteristic):
if notifying:
async_tools.add_timer_seconds(2, update_value, characteristic)
def main(adapter_address):
logger = logging.getLogger('localGATT'

本文介绍了如何使用Python在树莓派上创建蓝牙服务,包括模拟CPU温度读取和实现蓝牙UART通信。首先,通过安装`dbus-python`和`bluezero`库来准备环境。接着,展示了两个代码示例:一是创建一个模拟CPU温度读取的服务,用户可通过微信小程序等设备连接并获取温度数据;二是实现一个蓝牙UART设备,用于接收和发送数据,支持写入和通知功能。这两个例子为开发基于树莓派的蓝牙应用提供了基础。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



