如何使用 Python 从蓝牙低功耗传感器读取温度、湿度和压力值?

问题描述 投票:0回答:1

我正在开发一个 BLE 客户端,该客户端从连接到 ESP32C3 DevKit 的 TE MS8607 I2C 传感器读取温度、湿度和压力。我正在使用 BleakClient、Python 3.9 和 Asyncio。我定义了一个例程,从 ESP32 读取特征值并将其打印到串行监视器。这样可行。我现在想绘制返回值的重复读数,但到目前为止似乎无法将我打印出来的变量移动到我将数据附加到数组以进行绘制的主要位置。我尝试在程序的第一行创建tout,然后在我的get_THP中使用tout,但是该tout没有在我的main.c中更新。相反,我只看到初始化值。以下是一些代码片段。我已经尝试了几种使用 console.log(await get_THP()) 等建议来执行返回值的方法,但这似乎对我有用。

async def get_THP():
    client = BleakClient(address)
    try:
        await client.connect()
        TempC = await client.read_gatt_char(tempC_UUID)
        humidity = await client.read_gatt_char(humidity_UUID)
        pressure = await client.read_gatt_char(pressure_UUID)
        encoding='utf-8'
        tc = TempC.decode(encoding)
        tout=float(tc)
        h=humidity.decode(encoding)
        hout=float(h)
        p = pressure.decode(encoding)
        pout=float(p)
        print("%.1f degC"%tout)
        #...RETURNS THP VALUES TO MONITOR.

async def main(address):
    count=1
    maxpoints=3
    t1=datetime.datetime.now()
    interval=1
      
    while(1):
        
        print(count)
        await  get_THP()
        print(tout)
        #..DOES NOT GET THE VALUES
getData 中的 print(tout) 返回正确的值,但 main 中返回初始 0 值。如何#将返回值返回到我的主程序中?

希望将 ESP32 服务器的温度、湿度和压力返回读数传输到变量中,我可以将这些变量附加到之前的读数中,然后绘制随时间变化的值。我在循环 get_THP() 工作时确实有绘图和 asyncio.sleep 延迟。我仅使用 DateTime 来获取测量的当前时间。

python bluetooth-lowenergy sensors
1个回答
0
投票
我在理解异步时遇到了几个问题。大多数问题都是通过“async for”和迭代的 asyncio 定义解决的。原始代码尝试在 while 循环内检索数据,但失败了。新方法通过异步迭代从“async for”循环恢复 BLE 数据。这段代码解决了检索问题。

async def iterations(loops): for i in range(loops): yield i await asyncio.sleep(0.5) async def main(address): tout=0 pout=0 hout=0 ipause=10 loops=12 # total time of run is ipause*loops = approx 120 seconds tv=[] hv=[] pv=[] xtimes=[] async for i in iterations(loops): (tout,hout,pout)=await get_THP() await say_after(ipause,"waited ipause seconds") tv=np.append(tout,tv) hv=np.append(hout,hv) pv=np.append(pout,pv) xtimes=np.append((mdates.date2num(dt.datetime.now())),xtimes) print(i*ipause) plot(tv,hv,pv,xtimes) if __name__ == "__main__": asyncio.run(main(address))
    
© www.soinside.com 2019 - 2024. All rights reserved.