-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathS34_Task_Groups.py
More file actions
74 lines (64 loc) · 2.32 KB
/
S34_Task_Groups.py
File metadata and controls
74 lines (64 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File: main.py
# Author: Armstrong Subero
# Platform: Raspberry Pi Pico (RP2040) with MicroPython
# Program: S34_Task_Groups
# Interpreter: MicroPython (latest version)
# Program Version: 1.0
#
# Program Description: This program allows the Raspberry Pi Pico to
# demonstrate use of async and await to create
# a taskgroup, we mimic the behavior of a cancellation
# by using another coroutine
#
# Hardware Description: LEDs are connected via 1k resistors to GP16 and GP17
#
# Created: August 23rd, 2024, 11:36 AM
# Last Updated: August 23rd, 2024, 11:36 AM
import uasyncio as asyncio
from machine import Pin
# Define GPIO pins for LEDs
LED_ONE = 16
LED_TWO = 17
# Set up the LEDs as output pins
led1 = Pin(LED_ONE, Pin.OUT)
led2 = Pin(LED_TWO, Pin.OUT)
async def blink_led1():
try:
while True:
led1.toggle()
print("LED 1 toggled")
await asyncio.sleep(1) # Blink every 1 second
except asyncio.CancelledError:
print("blink_led1 was cancelled")
raise # Re-raise the exception if you want to propagate the cancellation
async def blink_led2():
try:
while True:
led2.toggle()
print("LED 2 toggled")
await asyncio.sleep(2) # Blink every 2 seconds
except asyncio.CancelledError:
print("blink_led2 was cancelled")
raise # Re-raise the exception if you want to propagate the cancellation
async def cancel_task(task, delay):
"""Cancel a given task after a delay."""
await asyncio.sleep(delay)
print(f"Cancelling task after {delay} seconds")
task.cancel() # Cancel the task
async def main():
# Create tasks manually
task1 = asyncio.create_task(blink_led1())
task2 = asyncio.create_task(blink_led2())
# Simulate cancellation of task1 after 5 seconds
asyncio.create_task(cancel_task(task1, 5))
try:
await asyncio.sleep(10) # Run for 10 seconds
except asyncio.CancelledError:
print("main was cancelled")
finally:
task1.cancel() # Ensure task 1 is canceled if not already
task2.cancel() # Cancel task 2
await asyncio.gather(task1, task2, return_exceptions=True)
print("Tasks were cancelled")
# Run the main function
asyncio.run(main())