// 替换数据生成部分为传感器读取voidupdateSensorData(){float temperature = dht.readTemperature();float humidity = dht.readHumidity();// JSON格式数据String sensorData ="{\"temp\":"+String(temperature)+",\"humidity\":"+String(humidity)+"}";readOnlyCharacteristic.writeValue(sensorData.c_str());Serial.println("Sensor data updated: "+ sensorData);}
三、树莓派 Python BLE 客户端详解
1. bleak_scan.py - BLE设备扫描
# 作用:扫描周围BLE设备# 应用:发现Arduino设备import asyncio
from bleak import BleakScannerasyncdefscan_ble_devices():print("Scanning for BLE devices...")devices =await BleakScanner.discover(timeout=5.0)ifnot devices:print("No BLE devices found.")else:print("Found devices:")for d in devices:print(f"{d.address} - {d.name}")# 运行扫描
asyncio.run(scan_ble_devices())
2. bleak_name_conn.py - 按名称连接
# 作用:通过设备名称连接并读取特征# 应用:连接特定Arduino设备import asyncio
from bleak import BleakScanner, BleakClient# 目标设备名称片段
TARGET_NAME_FRAGMENT ="ArduinoSensor"# 改为你的设备名# 特征UUID(必须与Arduino一致)
CHARACTERISTIC_UUID ="19B10001-E8F2-537E-4F6C-D104768A1214"asyncdefscan_and_connect():print("Scanning for BLE devices...")devices =await BleakScanner.discover(timeout=5.0)# 查找目标设备target_device =Nonefor d in devices:if d.name and TARGET_NAME_FRAGMENT in d.name:target_device = dbreakifnot target_device:print(f"No device found with name containing '{TARGET_NAME_FRAGMENT}'.")returnprint(f"Found target: {target_device.name} ({target_device.address})")# 连接并读取数据asyncwith BleakClient(target_device.address)as client:if client.is_connected:print("Connected successfully.")try:# 读取特征值value =await client.read_gatt_char(CHARACTERISTIC_UUID)print(f"Raw value: {value}")# 尝试解码为字符串try:decoded_value = value.decode('utf-8')print("Decoded value:", decoded_value)except:print("Value is not UTF-8 string")except Exception as e:print("Failed to read characteristic:", e)else:print("Failed to connect.")asyncio.run(scan_and_connect())
3. bleak_rec_notify.py - 接收通知
# 作用:订阅特征通知并实时接收数据# 应用:实时接收传感器数据import asyncio
from bleak import BleakScanner, BleakClient# 目标设备名称片段
TARGET_NAME_FRAGMENT ="ArduinoSensor"# 特征UUID
CHARACTERISTIC_UUID ="19B10001-E8F2-537E-4F6C-D104768A1214"# 通知处理函数defhandle_notification(sender, data):print(f"[Notification] From {sender}: {data}")try:# 解码JSON数据(需要)decoded_data = data.decode('utf-8')print("Decoded:", decoded_data)# 在这里添加MQTT发布逻辑# mqtt_client.publish("sensors/dht", decoded_data)except Exception as e:print("Decoding error:", e)asyncdefscan_connect_and_subscribe():print("Scanning for devices...")devices =await BleakScanner.discover(timeout=5.0)# 查找设备target_device =Nonefor d in devices:if d.name and TARGET_NAME_FRAGMENT in d.name:target_device = dbreakifnot target_device:print(f"No device found with name containing '{TARGET_NAME_FRAGMENT}'.")returnprint(f"Found device: {target_device.name} ({target_device.address})")# 连接并订阅通知asyncwith BleakClient(target_device.address)as client:if client.is_connected:print("Connected successfully.")try:# 启动通知订阅await client.start_notify(CHARACTERISTIC_UUID, handle_notification)print("Subscribed to notifications. Press Ctrl+C to stop.")# 保持连接,持续接收数据whileTrue:await asyncio.sleep(1)except Exception as e:print("Failed to subscribe:", e)else:print("Failed to connect.")try:asyncio.run(scan_connect_and_subscribe())except KeyboardInterrupt:print("Program stopped by user.")