micropython ble 连接小米温湿度计2 获取数据
在MicroPython中,要通过BLE连接到小米温湿度计2并获取数据,你需要使用micropython
的ble
库。以下是一个简单的示例代码,它会扫描BLE设备,连接到小米温湿度计2,并获取温度和湿度数据。
from machine import Pin
from micropython import const
from ble_advertising import Advertising
# 定义小米温湿度计2的服务UUID
TEMPERATURE_SERVICE_UUID = const(0x181A)
HUMIDITY_SERVICE_UUID = const(0x181A)
# 定义温度和湿度的特征UUID
TEMPERATURE_CHARACTERISTIC_UUID = const(0x2A6E)
HUMIDITY_CHARACTERISTIC_UUID = const(0x2A6F)
# 初始化BLE适配器
ble = Advertising()
# 连接小米温湿度计2
def connect_to_xiaomi_hygrothermograph_2():
# 扫描可用的BLE设备
for adv in ble.scan():
if 'xiaomi' in adv.name and 'Hygrothermograph 2' in adv.name:
# 连接到小米温湿度计2
central = ble.connect(adv)
# 获取服务
temp_service = central.service(TEMPERATURE_SERVICE_UUID)
humidity_service = central.service(HUMIDITY_SERVICE_UUID)
# 获取特征
temperature_characteristic = temp_service.characteristic(TEMPERATURE_CHARACTERISTIC_UUID)
humidity_characteristic = humidity_service.characteristic(HUMIDITY_CHARACTERISTIC_UUID)
# 读取温度和湿度数据
temperature = temperature_characteristic.read()
humidity = humidity_characteristic.read()
# 断开连接
central.disconnect()
# 返回温度和湿度数据
return temperature, humidity
# 调用连接函数
temperature, humidity = connect_to_xiaomi_hygrothermograph_2()
# 显示温度和湿度数据
print(f"Temperature: {temperature[0]}°C, Humidity: {humidity[0]}%")
确保你的设备支持BLE,并且你的MicroPython固件已经包含了ble_advertising
库。这个示例假设你的设备上有一个BLE适配器,并且它的名字包含"xiaomi"和"Hygrothermograph 2"。根据你的设备和固件版本,可能需要对代码进行适当的调整。
评论已关闭