calling functions within an interrupt

Discussion in 'Embedded Systems and Microcontrollers' started by bug13, May 27, 2013.

  1. bug13

    Thread Starter Senior Member

    Feb 13, 2012

    I know that it is not a good idea to call a function within interrupt, but using functions can make my life a lot easier. so if I really want to call functions within interrupt, what are the limitations, and what should I avoid?

    or what do I need to do to call a function in a safe way within interrupt.

  2. MrChips


    Oct 2, 2009
    There is nothing wrong with calling functions within an interrupt, except perhaps the following:

    1) Some chips (particularly PICs) have a limit to how many calls can be nested.

    2) In a complex real time operating system you want to execute the interrupt service routine (ISR) as quickly as possible and then get out. If you are calling another function perhaps this is a sign that you are spending too much time in the ISR.

    3) Whatever function you are calling must be reentrant. For example, suppose your program outside of the ISR has already entered the function. What happens if the ISR calls the same function which is already invoked outside of the ISR?
    Eric007 and bug13 like this.
  3. tshuck

    Well-Known Member

    Oct 18, 2012
    Provided you don't go and try to call more functions than the stack has room for(I think most compilers will throw an error if you try to exceed the stack length), not to mention the fact that other interrupts are disabled(unless using interrupts with different hardware priorities) and that the processor has to spend a large amount of time(relatively) responding to an interrupt, it should be fine, however those limitations are pretty huge...
    bug13 likes this.
  4. bug13

    Thread Starter Senior Member

    Feb 13, 2012
    OK, that's how I understand reentrant, a reentrant function is a function doesn't use any static or global variable.

    So if I make any access to static or global variables outside a interrupt an atomic block, is that good enough?
  5. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    Blowing the stack isn't a concern with most compilers as they do not use the hardware stack; they create a software stack in RAM that can be very large.

    Global variables are the big problem as they appear in places you do not suspect, such as any mathematical function (+ - * /) as they use the internal functions to hold intermediate sums.
    bug13 likes this.