python中将小米手环中读取的心率每隔一秒多行写到txt文件,使用bleak库来连接蓝牙设备并接收心率
时间: 2024-12-23 13:14:21 浏览: 19
在Python中,使用bleak库连接小米手环并实时读取心率,然后每秒将数据追加到文本文件中,你需要做以下几个步骤:
1. 首先,确保安装了必要的库,包括`bleak`, `schedule`用于定时任务,以及`datetime`处理时间戳。可以使用以下命令安装:
```bash
pip install bleak schedule
```
2. 导入所需的库:
```python
import time
from bleak import BleakClient
import datetime
import schedule
```
3. 定义连接到手环并获取心率的数据回调函数:
```python
def read_heart_rate(client):
service_uuid = "180d" # 小米手环心率服务UUID
characteristic_uuid = "0x76" # 心率测量值UUID
def callback(handle, value):
heart_rate = int.from_bytes(value, byteorder="little")
write_to_file(heart_rate)
client.start_notify(service_uuid, characteristic_uuid, callback)
```
4. 实现写入文件的函数:
```python
def write_to_file(heart_rate):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("heart_rate_log.txt", "a") as file:
file.write(f"{timestamp}: {heart_rate}\n")
```
5. 创建并启动蓝牙客户端,连接到手环,并设置每秒读取一次心率:
```python
async def connect_and_read():
try:
device_address = "your_device_address" # 替换为你小米手环的地址
client = BleakClient(device_address)
await client.connect()
print(f"Connected to {device_address}")
read_heart_rate(client)
while True:
schedule.run_pending() # 每秒检查是否有新的任务需要运行
await client.read_gatt_value(characteristic_uuid) # 模拟每秒读取
time.sleep(1)
except Exception as e:
print(f"Error: {e}")
finally:
client.disconnect()
print("Disconnected from the device.")
# 启动任务
schedule.every(1).seconds.do(connect_and_read)
```
记得替换第15行的`device_address`为你的小米手环的实际地址。这个脚本会无限循环地读取和记录心率数据到`heart_rate_log.txt`文件,每秒钟一行。
阅读全文