Skip to main content

Posts

Showing posts with the label MicroPython

MicroPython ISR Constraints: Handling 'MemoryError' and Heap Allocation Inside Interrupts

  You have wired up a simple push button to an ESP32 or a Raspberry Pi Pico. You attach an interrupt handler to detect the rising edge, and inside that handler, you attempt a simple operation: logging a message with a timestamp or appending a sensor reading to a list. The moment the button is pressed, your microcontroller panics:  MemoryError: memory allocation failed . This is the most common pitfall in embedded Python development. It occurs because you are treating a MicroPython Interrupt Service Routine (ISR) like a standard Python function. It is not. This post dissects the architectural constraints of the MicroPython heap during interrupts and provides the canonical solution using  micropython.schedule . The Root Cause: Re-entrancy and the Locked Heap To understand the error, you must understand the MicroPython memory model. In standard CPython (desktop), "interrupts" are actually signal handlers handled by the main loop. In MicroPython running on bare metal, interru...