首页 > 解决方案 > Micropython - 如何在后台接收数据

问题描述

我正在使用带有 MicroPython 的 ESP8266(Wemos D1 mini)在 OLED 上显示我当地气象站的秒数和温度的实际时间。

代码片段

try:
    while True:

        now = utime.localtime()
        hour = str(now[3])
        minu  = str(now[4])
        secs  = str(now[5])
        actualtime = hour + ":" + minu + ":" + secs

        #clear OLED and display actualtime
        oled.fill(0)
        oled.textactualtime, 0, 0)

        #every 30 seconds get data from api
        if secs == '30':
            data = get_from_api(url)

        oled.text("Temperature: "+data["temp"]+ " C", 0, 45)    
        oled.show()
        sleep(1)

每分钟我都试图通过 url 请求获取实际温度。 问题是这个操作可能需要几秒钟,然后我的时钟会冻结而不是每秒显示时间。

如何在单独的进程/并行进程中获取此类数据以不减慢我的循环。

标签: pythonesp8266esp32micropython

解决方案


有几种方法可以做到这一点。

一种选择可能是使用 aTimer来更新您的 oled。

https://docs.micropython.org/en/latest/esp8266/quickref.html#timers

它可能看起来像这样。请注意,这不是工作代码,因为我只是复制并重新排列了您问题中的代码:

from machine import Timer
import micropython

data = None

def update_oled(_):
    now = utime.localtime()
    hour = str(now[3])
    minu  = str(now[4])
    secs  = str(now[5])
    actualtime = hour + ":" + minu + ":" + secs

    #clear OLED and display actualtime
    oled.fill(0)
    oled.textactualtime, 0, 0)

    if data != None:
        oled.text("Temperature: "+data["temp"]+ " C", 0, 45)

    oled.show()

def schedule_update_oled(_):
    micropython.schedule(update_oled, 0)

timer = Timer(-1)
timer.init(period=1000, mode=Timer.PERIODIC, callback=schedule_update_oled)

try:
    while True:
        data = get_from_api(url)
        sleep(30)
except KeyboardInterrupt:
    timer.deinit()

请注意,计时器是一个中断,因此在回调中包含太多代码不是一个好主意。您可能还需要使用schedule.

https://docs.micropython.org/en/latest/reference/isr_rules.html#using-micropython-schedule


另一种选择可能是将代码分解为不同的流:

https://docs.micropython.org/en/latest/library/uselect.html


推荐阅读