How to properly enable/disable interrupts in ARM Cortex-M?

Point of this post is not how to use NVIC (Nested Vectored Interrupt Controller) in Cortex-M processors but how to disable/enable interrupts properly for your system to avoid strange behaviours in your code.

Let’s assume you have 2 functions, which do some important stuff and they have to make sure that noone interrupts these 2 functions

By calling these 2 functions from some other function, this will just work properly, interrupts will be disabled, important stuff done and interrupts enabled again. But what if you come to a situation, when important function 1 calls important function 2 from section where function 1 should not be interrupted? In case above, important function 2 would enable interrupts back and function 1 would not be safe anymore. Check example below which will fail in order to make clean and safe program:

To avoid problems like this, the idea is that before you disable interrupts in your function, first check interrupt enabled status in Cortex-M4 PRIMASK register to see if they were enabled or disabled before. Check properly working example where you don’t have to worry about nested function calls with multiple interrupt enable or disable function calls:

GENERAL Library

If you are using my TM_GENERAL library for STM32F4xx and its Enable and Disable interrupts function, then you don’t have to worry about everything listed above, because these 2 functions are written in a way to avoid strange behaviour in your system. You can use it everywhere and they will work as expected. Download available below:

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...