pimoroni / pimoroni-pico

Libraries and examples to support Pimoroni Pico add-ons in C++ and MicroPython.
https://shop.pimoroni.com/collections/pico
MIT License
1.3k stars 494 forks source link

Managing PIO + module finalisers #197

Closed Gadgetoid closed 7 months ago

Gadgetoid commented 3 years ago

In MicroPython boards like Pico Unicorn should probably use a specific and documented state machine/PIO combo and always re-initialize it. Grabbing the first unused state machine on pio0 is only actually useful if we have enough PIO instruction memory to store the code... so it's not as if this is particularly helpful. The last-board-wins approach is probably - if not quite correct - much less prone to edge case errors.

There's currently no way to tear down PIO, DMA and other resources that have been allocated by a module - or a C++ class pretending to be a module - during a MicroPython soft reset condition. This causes weird bugs like that fixed in #196 where the module will churn through available state machines upon soft-reset until it hard faults.

Most modules could probably - since they wrap classes anyway - be converted to classes with finalisers, and we could add new ".py" files into "modules_py" that instantiate these classes and export their methods- effectively pretending to be a module, but with a benefit of a finaliser attached to the class for resource teardown.

Alternatively, does MicroPython for Pico need to be more aggressive about teardown on soft reset? Is this even possible?

TODO:

Gadgetoid commented 7 months ago

MicroPython kind-of has an answer for managing DMA, in the sense that it uses only shared handlers for interrupts, keeping track of those with MP_STATE_PORT. It also uses __del__ to clean up DMA channels.

As such the only really right way to manage DMA resources in MicroPython now, would be to use rp2_dma_make_new() outside of a C++ class, and pass the claimed channel in as a parameter. Since we're already very much not doing that, it's unlikely we'll adopt this approach. Right now DMA channels claimed in C/C++ and DMA channels claimed by MicroPython seem to coexist peacefully. Though those in C/C++ continue to need special care when cleaning up to avoid soft-resets burning DMA resources.

As for Pico Unicorn and its ilk, those are now classes and integrated with PicoGraphics.