How to Use Asyncio in MicroPython (Raspberry Pi Pico) | Digi-Key Electronics

Поділитися
Вставка
  • Опубліковано 25 лип 2024
  • 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: www.digikey.com/en/maker/proj...
    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: • Introduction to RTOS P...
    Product Links:
    Raspberry Pi Pico - www.digikey.com/en/products/d...
    Related Videos:
    Raspberry Pi Pico and RP2040 playlist - • Intro to Raspberry Pi ...
    Related Project Links:
    Getting Started with MicroPython (Raspberry Pi Pico) Part 1: Blink - www.digikey.com/en/maker/proj...
    Related Articles:
    What is a Real-Time Operating System (RTOS) - www.digikey.com/en/maker/proj...
    Introduction to MicroPython - www.digikey.com/en/maker/blog...
    Maker.io - www.digikey.com/en/maker
    Digi-Key’s Blog - TheCircuit www.digikey.com/en/blog
    Connect with Digi-Key on Facebook / digikey.electronics
    And follow us on Twitter / digikey
  • Наука та технологія

КОМЕНТАРІ • 26

  • @Yes-Man
    @Yes-Man Рік тому +9

    Holy ... you're the first person I found who actually knows what he's doing. I found so many blogs and tutorials out there just ignoring all the issues around multithreading while going about and writing "maker" code. Thanks for the clear instructions, although I already figured that stuff out by trial and error.

  • @heel57
    @heel57 4 місяці тому +1

    i like the stile of "no gossip" at the start.

  • @skf957
    @skf957 3 роки тому +17

    It amazes me that you always manage to present what are pretty complicated subjects in an entertaining and accessible way. Please don't stop what you are doing.

    • @zhouyu9971
      @zhouyu9971 Рік тому +3

      If any university runs this topic and hires this guy as a lecturer I’m pretty sure it’s gonna succeed! Not mention many other UA-camr, he’s actually teaching way better than many professional teachers

  • @lindsayf9230
    @lindsayf9230 2 роки тому

    Clear, detailed and practical! Thanks!

  • @johndeluca230
    @johndeluca230 Рік тому +1

    This is exactly what I was looking for as I'm pushing Pico's potential. Thanks!

  • @HopWorksET
    @HopWorksET 2 роки тому +1

    Another terrific video!! Very articulate, very easy to follow and understand. And you just happen to be covering the more complicated subjects I want to work with! Bravo! Thanks for your contribution and please continue, especially with the Pico!!!

  • @OmidAtaollahi
    @OmidAtaollahi 5 місяців тому

    asyncio is a great feature & you teach it very well❤

  • @sonnybalut
    @sonnybalut 2 роки тому

    Thank you for the tutorial.

  • @Factory400
    @Factory400 2 роки тому

    Great presentation of the topic! I wish this video happened a year ago when I first started learning about uasyncio. :-)

  • @michaeldobeck7261
    @michaeldobeck7261 3 роки тому +1

    Excellent!

  • @penttiitkonen9765
    @penttiitkonen9765 2 роки тому +1

    Great Shawn! Good thing to publish an MicroPython example how to run two things at the same time. The example could be called a asynchronous hello world.

  • @georgii2012
    @georgii2012 2 роки тому

    Спасибо! Очень Помогло!

  • @sudheerkumar5966
    @sudheerkumar5966 3 роки тому +1

    Very good

  • @alanb76
    @alanb76 Рік тому

    Good video!

  • @cprogrck
    @cprogrck 2 роки тому +1

    I highly recommend that folks implement PIOs on RP2040 before trying to do async stuff.

  • @SoggyCashew
    @SoggyCashew 2 роки тому

    In your example how would you stop the continuous loop of the LED using a button?

  • @BlueDolphinBlues
    @BlueDolphinBlues 2 місяці тому

    I'm trying to figure out where to get the cancel() method I need to cancel an async task then start a new one in it's place.

  • @billmoran3812
    @billmoran3812 3 роки тому +1

    This is the answer to a question that has been bugging me for months. It’s going to take a few iterations until it all sinks in, but at least I have a place to start.
    It seems unfortunate that there are two cores in the 2040 but we can only access one right now. I’m hoping Micropython can catch up to utilize both cores efficiently.

    • @samneggs1
      @samneggs1 2 роки тому

      I've been able to get the second core working in MicroPython with some success.
      ua-cam.com/video/8xjkKY_DDVI/v-deo.html
      As I mention in the description of the linked video continuous memory allocation will crash the second core, both cores actually. My main test is to temporarily add print(gc.mem_free()) which has to be stable. This means float point and many functions can't be used or need to be cached.
      For example I want to put a two digit number on a screen. The text() function I'm using requires a string. str() allocates memory so instead of this: text(str(number)) I had to do this:
      s=['0','1','2','3','4','5','6','7','8','9'] # this is outside the main loop
      s1=s[number//10]
      s2=s[number%10]
      text(s1)
      text(s2)

  • @sammlabra519
    @sammlabra519 Рік тому

    How can I press the button so it activates/deactivates led ? each action being a different task? Thanks. 🙂

  • @marinehm
    @marinehm Рік тому

    I get an error: 'Pin' object has no attribute 'toggle'

  • @naasikhendricks1501
    @naasikhendricks1501 Рік тому

    I am trying to find details on .mpy and viper to speed up micropython. Using windows and thonny. Kiss.

  • @deekaneable
    @deekaneable Рік тому

    pull a tucker carlson and ditch the bow

  • @AndersJackson
    @AndersJackson 2 роки тому

    Just to say, Erlang is way easier to do this. And it uses way less memory for each tasks.

  • @kippie80
    @kippie80 2 роки тому

    Ahh! what happened to you guys? A whole genetation of people that pronounce 'button' as butun.