VideoLibrary

How to Use Asyncio in MicroPython (Raspberry Pi Pico) | DigiKey

At this time, MicroPython does not support full multithreading (with the threading library). However, we can use uasyncio (the MicroPython version of the larger Python asyncio library) to create a cooperative multitasking program. Uasyncio contains a subset of functions found in the asyncio library. Some parts (like queues) are left out (at the time this video was released). In the video, we go over how cooperative multitasking compares to preemptive multitasking and how you can use uasyncio to create several tasks in a single program. Specifically, we will use the Raspberry Pi Pico to demonstrate how to read button presses in one loop and blink an LED in another loop. We will also show how to use a queue to pass messages between the tasks. The full code for this tutorial can be found here: https://www.digikey.com/en/maker/projects/getting-started-with-asyncio-in-micropython-raspberry-pi-pico/110b4243a2f544b6af60411a85f0437c Asyncio is based around the idea of “coroutines,” which behave like normal functions but have the ability to yield the processor. While a coroutine is paused, the processor is free to perform other activities. This is extremely useful to optimize processor utilization while waiting for things like a response from a sensor, website, etc. or while performing periodic tasks. We define coroutines using the “async” keyword, which lets the scheduler (a task that runs in the background in charge of telling other tasks to run) know that the containing function is capable of yielding. We can wait for a coroutine to finish executing with the “await” keyword. Finally, we can run a coroutine as a task (e.g. return immediately while letting the coroutine execute) using the create_task() function. Note that coroutines must be run as part of an “event loop” that includes a scheduler. The scheduler, unlike in preemptive multitasking, only runs when a coroutine explicitly yields (e.g. using the “await” keyword). As a result, the programmer must take great care to ensure that none of the coroutines hog the processor and starve the other coroutines/tasks. This method of “cooperative multitasking” makes it more difficult for (seemingly random) bugs to occur (such as race conditions when working with a preemptive scheduler). If you would like to learn more about preemptive multitasking, you can check out my Introduction to RTOS series here: https://www.youtube.com/watch?v=F321087yYy4

8/9/2021 2:41:41 PM

Part List

图片制造商零件编号描述可供货数量价格查看详情
RASPBERRY PI PICO RP2040SC0915RASPBERRY PI PICO RP20403845 - 立即发货$32.56查看详情