Add Macropad asyncio article
This commit is contained in:
parent
95f4f1a616
commit
8cf6983304
5 changed files with 639 additions and 0 deletions
|
@ -0,0 +1,52 @@
|
|||
from adafruit_macropad import MacroPad
|
||||
import usb_cdc, asyncio, random
|
||||
|
||||
macropad = MacroPad()
|
||||
macropad.pixels.brightness = 0.3
|
||||
run_color = 0xad20b4
|
||||
wait_color = 0x21f312
|
||||
|
||||
# déclaration de notre Mutex
|
||||
blink_mutex = asyncio.Lock()
|
||||
|
||||
async def get_key(taskslist):
|
||||
while True:
|
||||
key_event = macropad.keys.events.get()
|
||||
if key_event:
|
||||
if key_event.pressed:
|
||||
taskslist.append(asyncio.create_task(blink(key_event.key_number)))
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def blink(led):
|
||||
timer = random.random() * 3
|
||||
macropad.pixels[led] = wait_color
|
||||
if blink_mutex.locked():
|
||||
print("Wait for mutex l:{}".format(led))
|
||||
|
||||
await blink_mutex.acquire()
|
||||
|
||||
print("Aquire mutex l:{}".format(led))
|
||||
for _ in range(5):
|
||||
macropad.pixels[led] = run_color
|
||||
await asyncio.sleep(timer)
|
||||
macropad.pixels[led] = 0x0
|
||||
await asyncio.sleep(timer)
|
||||
|
||||
blink_mutex.release()
|
||||
|
||||
async def manage_tasks(taskslist):
|
||||
tasks = 0
|
||||
while True:
|
||||
for task_number in range(0, len(taskslist)):
|
||||
if taskslist[task_number].done():
|
||||
taskslist.pop(task_number)
|
||||
break
|
||||
await asyncio.sleep(0)
|
||||
|
||||
async def main():
|
||||
tasks = []
|
||||
tasks.append(asyncio.create_task(get_key(tasks)))
|
||||
tasks.append(asyncio.create_task(manage_tasks(tasks)))
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
asyncio.run(main())
|
Loading…
Add table
Add a link
Reference in a new issue