Why does my ISR callback work even though I am allocating memory?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
solarjoe
Posts: 11
Joined: Wed Oct 28, 2020 9:07 pm

Why does my ISR callback work even though I am allocating memory?

Post by solarjoe » Wed Oct 28, 2020 9:25 pm

Hello,

I have a question and hope that you can help me.
I am reading into ISR callbacks in the Micropython docs at the moment.
(https://docs.micropython.org/en/latest/ ... rules.html)

While the recommendation to allocate memory outside of the callbacks using

Code: Select all

array
or

Code: Select all

bytearray
makes total sense to me, I could not help but to try what happens if I do that :)

And - everything works like a charm... I have no clue why or if this is some special case.
Can someone enlighten me? I really tried to break every rule I found in the docs and expected Python to complain like hell.

Code: Select all

from machine import Pin, I2C
import machine

import micropython
micropython.alloc_emergency_exception_buf(100)

a = []

class SomeThing:
    pass

def callback(pin):

    global a
    a.append(True)
    b = 2.2
    x = SomeThing()
    c = 4.4
    print()
    print(pin)
    print(b + c)


p = machine.Pin(39, machine.Pin.IN, machine.Pin.PULL_UP)
trigger_all = Pin.IRQ_FALLING | Pin.IRQ_RISING

p.irq(trigger=trigger_all, handler=callback)

while True:
    pass

User avatar
jimmo
Posts: 2015
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Why does my ISR callback work even though I am allocating memory?

Post by jimmo » Wed Oct 28, 2020 11:49 pm

solarjoe wrote:
Wed Oct 28, 2020 9:25 pm
I have no clue why or if this is some special case.
It depends which board/port you're using.

On ESP32 for example, all IRQs are "soft" which means they run in the MicroPython scheduler.

In general, the foo.irq(..., hard=) kwarg lets you control whether an IRQ is hard (runs in true interrupt context, no allocations) or soft (not very many restrictions). See http://docs.micropython.org/en/latest/l ... ne.Pin.irq. On ESP32 this kwarg is ignored because it must always be soft, but for example Pyboard/STM32 lets you use either.

solarjoe
Posts: 11
Joined: Wed Oct 28, 2020 9:07 pm

Re: Why does my ISR callback work even though I am allocating memory?

Post by solarjoe » Thu Oct 29, 2020 7:09 am

ESP32 this kwarg is ignored
Thanks for your answer, that was new to me.

Code: Select all

Pin.irq(..., hard=False)

hard: Hard interrupt handlers may not allocate memory; see Writing interrupt handlers. Not all ports support this argument.

Post Reply