IOT

Micropython: 解决Esp8266没有多线程,使用异步的方式执行多个任务

最近在公司业务需要用到一个硬件模块,上面有这样1个功能需要一直在循环执行,但是这个功能不能阻塞掉其他功能的执行。
想到这里,有人肯定会说,用多线程啊,但是它没有啊。

于是我做了一番调查,mpy有个自带的uasyncio模块可以解决这个问题,上帝给你关上一扇门的时候就给你开了个窗。

开干(上代码示例):

import uasyncio as asyncio


async def loop_task(arg):
    while True:
        print('{0} 状态1'.format(arg))
        await asyncio.sleep(1)
        print('{0} 状态2'.format(arg))
        await asyncio.sleep(1)


async def other_task():
    print('我是其他非阻塞任务')
    await asyncio.sleep(1)


def main():
    loop = asyncio.get_event_loop()
    loop.create_task(loop_task('死循环'))
    loop.create_task(other_task())

    loop.run_forever()


if __name__ == '__main__':
    main()

OK, all done, enjo!!!

This is just a placeholder img.