python - 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 请求获取实际温度。 问题是这个操作可能需要几秒钟,然后我的时钟会冻结而不是每秒显示时间。
如何在单独的进程/并行进程中获取此类数据以不减慢我的循环。
解决方案
有几种方法可以做到这一点。
一种选择可能是使用 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
另一种选择可能是将代码分解为不同的流:
推荐阅读
- javascript - 更改第一个对象中的值会导致第二个对象更改
- ios - 使用经典 BT 和 BLE 与同一外围设备通信时出现“对等删除配对信息”错误
- python - 如何在两个限制之间整合一个数组
- c# - 实体框架 DateTime 具有毫秒差异,而数据保留在数据库中
- python - 从具有特定模式的字符串中获取子字符串
- javascript - 我在哪里把我的配置放在这个 axios 请求中?
- python - 拆分字符串直到第一次遇到数字和“:”
- docker - 运行最新的 Docker ColdFusion 映像时浏览器请求挂起
- azure-bot-service - 机器人作曲家-发布到 Azure-位置 0 的 JSON 中的意外令牌 E
- php - 如何在单个php页面中调用多个sql存储过程