I'm attempting to learn asyncio. But I'm stumped on the behaviour uasyncio.sleep(0) in this case.
The code below is my first exercise to get a grasp of asyncio programming. The code simply flashes the two ESP8266 nodemcu onboard LEDs continiously at different rates. I have posted two version of the code. The first example works, but the second doesn't. Please see the differences in the main() coro. I thought that await uasyncio.sleep(0) would allow the coro loops to run continuously on the second example. If not, please let me know the best and/or correct way to implement this.
Thanks
This works
Code: Select all
#ESP8266 asyncio dual led continuous flasher
from machine import Pin
import uasyncio
led1 = Pin(2, Pin.OUT, value=1) # built in nodemcu LEDs
led2 = Pin(16, Pin.OUT, value=1)
async def blink():
while True:
led1.off()
await uasyncio.sleep(1)
led1.on()
await uasyncio.sleep(1)
async def blink_2():
while True:
led2.off()
await uasyncio.sleep(.25)
led2.on()
await uasyncio.sleep(.25)
async def main():
uasyncio.create_task(blink())
await uasyncio.create_task(blink_2()) # this works
uasyncio.run(main())
Code: Select all
#ESP8266 asyncio dual led continuous flasher
from machine import Pin
import uasyncio
led1 = Pin(2, Pin.OUT, value=1) # built in nodemcu LEDs
led2 = Pin(16, Pin.OUT, value=1)
async def blink():
while True:
led1.off()
await uasyncio.sleep(1)
led1.on()
await uasyncio.sleep(1)
async def blink_2():
while True:
led2.off()
await uasyncio.sleep(.25)
led2.on()
await uasyncio.sleep(.25)
async def main():
uasyncio.create_task(blink())
uasyncio.create_task(blink_2())
await uasyncio.sleep(0) # this doesn't work
uasyncio.run(main())