Reputation: 15042
Is it possible to determine whether a method in FreeRTOS is being invoked from the context of an ISR (interrupt service request) or a task at runtime? Maybe an existing function already exists for this or maybe it is possible to write a method that examines the stack somehow?
Upvotes: 2
Views: 3370
Reputation: 9620
There are two ways to do this. I'm using a Cortex-M7 microcontroller. So I'm not 100% sure this works for your Cortex-M3. But it's worth checking in your datasheets.
FIRST APPROACH Check the CPU registers of your Cortex-M core. Normally you have the usual R0-R12 CPU registers, a SP (Stack Pointer), a LR (Link Register) and a PC (Program Counter). There are a few extra 'special' CPU registers, more specifically: PSR, PRIMASK, FAULTMASK, BASEPRI and CONTROL. That's it for the Cortex-M7 core. Now consider the PSR register. The PSR register stands for "Program Status Register". There is a bitfield ISR_NUMBER[8:0] in it. If it has the value 0, the CPU is in "thread mode". Thread mode is the normal non-interrupt mode. If the value is nonzero, your CPU is executing an interrupt. What interrupt? The value in ISR_NUMBER[8:0] tells you the interrupt number. Reading the value of the PSR register is not trivial. You need to use specific assembly instruction to do that. There is no quick way to do it in C. You will need the MSR (Move general to special reg) and MRS (move special to general reg) instructions. Of course, inline assembly will make it possible to put it smoothly in your C-code :-)
SECOND APPROACH There is a second approach. Unlike the previous one, you don't need to read out a CPU register. Instead, this second approach requires you to read out the value of a 'general' register (like there are a few thousand in your microcontroller). The register I'm referring to is the ICSR(Interrupt Control and State) register. This register is located in the SCB "System Control Block". The register has a bitfield named VECTACTIVE[8:0]. Again, this bitfield contains the number of the active interrupt. If the value is 0, the CPU is in thread mode, which means that no interrupt is currently running.
Hope this helps.
Upvotes: 2