Get interrupt execution status on Cortex-M processors

You might come to a situation when you wanna know if current code is executing inside interrupt or not. This might be handy when you do a library and you have one function which you wanna call in interrupt handler for specific event or without interrupt handler, buf wanna execute something specific in function only if you are currently in interrupt. You can create 2 different functions of course, but what if you have one very big function, and for example when you are in interrupt, you wanna just do something small inside function somewhere at the middle?

Then you wanna know if you are executing code within interrupt or not. Cortex-M processors have special section SCB (System Control Block) inside. ICSR (Interrupt Control and State Register) register inside this section can be used to detect, if there is currently active any interrupt handler or not. Below is image of ICSR register for Cortex-M4 processor (Have in mind that all Cortex-M processors uses bottom 9 bits to detect proper interrupt number currently executing).

ARM Cortex-M SCB ICSR register structure. From arm.com

ARM Cortex-M SCB ICSR register structure. From arm.com

VECTACTIVE bits of ICSR register told us which interrupt is active, it’s value is as follow:

  • 0: Interrupt is not active, we are in thread mode
  • > 0: Interrupt is active, not in thread mode

So, the idea is to read this bits from register and if result is more than zero, we are currently executing from interrupt source.

Example

Bottom example runs on STM32F401-Nucleo board and shows principle how to check if current execution is inside interrupt or not. It calls the same function inside interrupt and in main function (thread mode).

Result after some time

Result after some time



 

tilz0R

Owner of this site. Application engineer, currently employed by STMicroelectronics. Exploring latest technologies and owner of different libraries posted on Github.

You may also like...