0
0
FreeRTOSprogramming~5 mins

Critical sections and interrupt disabling in FreeRTOS

Choose your learning style9 modes available
Introduction

Critical sections help protect important code from being interrupted. This keeps data safe and programs running smoothly.

When you need to update shared data without interference from other tasks or interrupts.
When you want to prevent an interrupt from causing problems during a sensitive operation.
When multiple tasks might access the same resource and you want to avoid conflicts.
When you want to make sure a sequence of instructions runs all at once without being stopped.
When you want to keep the system stable by controlling when interrupts can happen.
Syntax
FreeRTOS
taskENTER_CRITICAL();
// critical code here
taskEXIT_CRITICAL();

taskENTER_CRITICAL() disables interrupts to protect the code inside.

taskEXIT_CRITICAL() re-enables interrupts after the critical code finishes.

Examples
This example safely increases a shared variable without interruption.
FreeRTOS
taskENTER_CRITICAL();
sharedVariable++;
taskEXIT_CRITICAL();
Protects multiple updates to shared resources as one atomic operation.
FreeRTOS
taskENTER_CRITICAL();
// update multiple shared resources
resource1 = newValue1;
resource2 = newValue2;
taskEXIT_CRITICAL();
Wraps a function call that changes shared data to avoid interruptions.
FreeRTOS
taskENTER_CRITICAL();
// critical section with function call
updateSharedData();
taskEXIT_CRITICAL();
Sample Program

This program shows how to safely increase a shared counter using a critical section to disable interrupts during the update.

FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>

volatile int sharedCounter = 0;

void incrementCounter() {
    taskENTER_CRITICAL();
    sharedCounter++;
    taskEXIT_CRITICAL();
}

int main() {
    printf("Before increment: %d\n", sharedCounter);
    incrementCounter();
    printf("After increment: %d\n", sharedCounter);
    return 0;
}
OutputSuccess
Important Notes

Always keep critical sections as short as possible to avoid slowing down the system.

Do not call blocking functions inside critical sections because it can cause system problems.

Use critical sections only when necessary to protect shared data or hardware access.

Summary

Critical sections stop interrupts to protect important code.

Use taskENTER_CRITICAL() and taskEXIT_CRITICAL() to mark critical sections.

Keep critical sections short and simple for best system performance.