树莓派(ZeroW或4B)(原生蓝牙)BLE低功耗蓝牙python示例(Peripheral 从机模式、GATT Server)

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

从机模式:例如微信小程序上蓝牙搜索树莓派蓝牙服务,配对连接。然后访问树莓派蓝牙提供的服务。

一、安装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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值