Micropython如何在后台获取接收数据

2024-04-29 08:27:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用ESP8266(wemosd1 mini)和MicroPython在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请求获得实际温度。 问题是,此操作最多需要几秒钟,然后我的时钟冻结,没有每秒钟显示一次时间。

如何在独立进程/并行进程中获取此类数据,以不减慢我的循环。你知道吗


Tags: fromapiurldataget时间温度now
1条回答
网友
1楼 · 发布于 2024-04-29 08:27:19

有几种方法可以做到这一点。你知道吗

一种选择可能是使用Timer更新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

相关问题 更多 >