Interrupts let a microcontroller stop what it's doing to handle important tasks quickly. Enabling and disabling interrupts controls when these quick responses can happen.
0
0
Enabling and disabling interrupts in Embedded C
Introduction
When you want the microcontroller to react immediately to a button press.
When you need to pause interrupts to safely update shared data.
When setting up hardware timers that trigger actions automatically.
When you want to avoid interruptions during critical code sections.
When managing communication protocols that rely on interrupts.
Syntax
Embedded C
/* Enable interrupts */ __enable_irq(); /* Disable interrupts */ __disable_irq();
These functions are often provided by the microcontroller's library or CMSIS.
Disabling interrupts stops all maskable interrupts until they are enabled again.
Examples
This turns on all maskable interrupts so the CPU can respond to them.
Embedded C
/* Enable interrupts globally */
__enable_irq();This stops all maskable interrupts temporarily.
Embedded C
/* Disable interrupts globally */
__disable_irq();Use this to protect important code from being interrupted.
Embedded C
/* Disable interrupts, do critical work, then enable again */
__disable_irq();
// critical code here
__enable_irq();Sample Program
This program shows disabling interrupts before a critical task and enabling them after. The print statements show the flow.
Embedded C
#include <stdio.h> #include "cmsis_gcc.h" // Assume this header provides __enable_irq and __disable_irq int main() { printf("Interrupts disabled.\n"); __disable_irq(); // Critical section: no interrupts allowed printf("Performing critical task...\n"); __enable_irq(); printf("Interrupts enabled.\n"); return 0; }
OutputSuccess
Important Notes
Always re-enable interrupts after disabling them to avoid missing important events.
Disabling interrupts for too long can cause missed signals or slow system response.
Some microcontrollers have different ways to enable/disable specific interrupts instead of all.
Summary
Interrupts let the CPU handle urgent tasks quickly.
Use __enable_irq() to allow interrupts and __disable_irq() to stop them temporarily.
Disable interrupts only when necessary and keep the disabled time short.