Page 1 of 1

Exit micropython from interrupt in c

Posted: Fri Oct 14, 2016 1:10 pm
by kapsky
Hello.
1. My uPy code is running in while loop.
2. I have timer interrupt implemented in c

- Is it possible to exit (break) executing uPy code from interrupt in c ?

I tried with: mp_obj_t exc = mp_obj_new_exception(&mp_type_SystemExit);
nlr_raise(exc);

which is sys.exit() function in uPy. After executing this code every interrupt is not working any more.


-I tried also this:
In interrupt global flag can be set.
Then I implemented my uPy module function which is checking if global flag is set. If yes its executing sys.exit().
In every while in uPy code I am checking the global flag. It works but I need to put addition code to every while loop.

- Is it possible to call sys.exit() in uPy interrupt ? My board is not ported and I cannot check it.

- I was also thinking about putting flags in place where script is interpreting, but I dont know where and I think, this is a lot of work.

If you have any idea let me know. Thank you !

Re: Exit micropython from interrupt in c

Posted: Fri Oct 14, 2016 3:49 pm
by dhylands
You can reset the processor from within an ISR using pyd.hard_reset() or machine.reset(). Otherwise, you'd need to set a flag and have the main script exit when it detects that flag is set.

Re: Exit micropython from interrupt in c

Posted: Mon Oct 17, 2016 6:47 am
by kapsky
Yes. I already have this solution with flag. But it is necessery to put condition in every while loop in script. I want to avoid this.
After exit script I need to continue code in C. So I cannot reset uC in interrupt.

Thank you for reply Dave !

Re: Exit micropython from interrupt in c

Posted: Mon Oct 17, 2016 8:37 am
by pythoncoder
One approach to checking the flag would be to write your Python code using cooperative multi tasking. The flag could then be tested by a thread running in an infinite loop, testing the flag and yielding to the main thread. If the flag is set, it terminates the program. The preferred way to do this is using uasyncio.

Re: Exit micropython from interrupt in c

Posted: Tue Oct 18, 2016 2:15 pm
by kapsky
Thanks for advise.
Im working on Infineon board and its not completly ported. Its a nice solution but I will use it if I will really need it.

You write to terminate program in thread. Is it possible to terminate program for example from pyb.Timer callback ?
If yes I can check flag and terminate program from callback. (but still need to port Timer functions)

Re: Exit micropython from interrupt in c

Posted: Sat Oct 22, 2016 1:39 am
by tannewt
Take a look at mp_keyboard_interrupt it interrupts python code from a C interrupt.

Re: Exit micropython from interrupt in c

Posted: Sat Oct 22, 2016 6:30 am
by pythoncoder
If you want a program to terminate after a given period of runing, look at (for example) ledflash.py here https://github.com/peterhinch/Micropython-scheduler.git.