Miscellaneous Topics
Interrupt Service Routines – Coding Suggestions
Listed below are a number of required and/or good coding practices to keep in mind when writing
hardware interrupt service routines. Many of these have been discussed elsewhere in this
chapter.
Hardware ISR’s – Coding Practices
An interrupt routine must be declared with no arguments and must return void
Do not call interrupt handling functions directly (Rather, write to IFG bit)
Interrupts can be handled directly with C/C++ functions by using the the
interrupt keyword or pragma
… Conversely, the TI-RTOS kernel easily manages Hwi context
Calling functions in an ISR
If a C/C++ interrupt routine doesn’t call other functions, only those registers that
the interrupt handler uses are saved and restored.
However, if a C/C++ interrupt routine does call other functions, the routine saves
all the save-on-call registers if any other functions are called
Why? The compiler doesn’t know what registers could be used by a nested
function. It’s safer for the compiler to go ahead and save them all.
Re-enable interrupts? (Nesting ISR’s)
DON’T – it’s not recommended – better that ISR’s are “lean & mean”
If you do, change IE masking before re-enabling interrupts
Disable interrupts before restoring context and returning (RETI re-enables int’s)
Beware – Only You Can Prevent Reentrancy…
We wrote the last bullet, regarding reentrancy, in a humorous fashion. That said, it speaks to an
important point. If you decide to enable interrupt nesting, you need to be careful that you either
prevent reentrancy - or that your code is capable of reentrancy.
Wikipedia defines reentrancy as:
In computing, a computer program or subroutine is called reentrant if it can be interrupted in the middle of its
execution and then safely called again ("re-entered") before its previous invocations complete execution.
This type of program/system error can be very difficult to debug (i.e. find and fix). This is
especially true if you call functions within your interrupt service routines. For example, the C
language’s malloc() function is not reentrant. If you were to call this function from an ISR and it
was interrupted, and then it is called again by another ISR, your system would most likely fail –
and fail in a way that might be very difficult to detect.
So, we stated this humorously, but it is very true. We recommend that:
• You shouldn’t nest interrupts
• If you do, verify the code in your ISR is reentrant
• Never call malloc() – or similar functions - from inside an ISR
MSP430 Workshop - Interrupts 5 - 29