Last active
November 18, 2023 00:52
-
-
Save anecdata/9b801165a784f823cee33b1b70e01571 to your computer and use it in GitHub Desktop.
CircuitPython asyncio with task added later
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#3 no gather, and add a task later | |
import board | |
import digitalio | |
import asyncio | |
import adafruit_ticks | |
led_pins = [board.A0, board.A1, board.A2, board.A3] | |
extra_led_pin = board.D24 | |
async def do_led(pin): | |
led = digitalio.DigitalInOut(pin) | |
led.switch_to_output(False) | |
while True: | |
led.value = not led.value | |
await asyncio.sleep(led_pins.index(pin) + 0.25) | |
async def main(): | |
tasks = [] | |
for taskno in range(len(led_pins)): | |
tasks.append(asyncio.create_task(do_led(led_pins[taskno]))) | |
done_once = False | |
t = adafruit_ticks.ticks_ms() | |
# This will run forever, because no tasks ever finish. | |
# await asyncio.gather(*tasks) | |
while True: | |
# add a task after running for a bit | |
# move this to its own task, and delete that task when done once... | |
if not done_once and (adafruit_ticks.ticks_ms() - t > 10_000): # 10 sec | |
led_pins.append(extra_led_pin) | |
tasks.append(asyncio.create_task(do_led(led_pins[-1]))) | |
done_once = True | |
await asyncio.sleep(0) | |
asyncio.run(main()) |
#2 no gather, all tasks created at the start
import board
import digitalio
import asyncio
led_pins = (board.A0, board.A1, board.A2, board.A3)
extra_led_pin = board.D24
async def do_led(pin):
led = digitalio.DigitalInOut(pin)
led.switch_to_output(False)
while True:
led.value = not led.value
await asyncio.sleep(led_pins.index(pin) + 0.25)
async def main():
tasks = []
for taskno in range(len(led_pins)):
tasks.append(asyncio.create_task(do_led(led_pins[taskno])))
# This will run forever, because no tasks ever finish.
# await asyncio.gather(*tasks)
while True:
await asyncio.sleep(0)
asyncio.run(main())
#1 canonical version, with gather
import board
import digitalio
import asyncio
led_pins = (board.A0, board.A1, board.A2, board.A3)
extra_led_pin = board.D24
async def do_led(pin):
led = digitalio.DigitalInOut(pin)
led.switch_to_output(False)
while True:
led.value = not led.value
await asyncio.sleep(led_pins.index(pin) + 0.25)
async def main():
tasks = []
for taskno in range(len(led_pins)):
tasks.append(asyncio.create_task(do_led(led_pins[taskno])))
# This will run forever, because no tasks ever finish.
await asyncio.gather(*tasks)
asyncio.run(main())
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
async_leds.mov
(yellow wire is connected to
board.D24
)