📖 Scenario: You are working on a FreeRTOS project where multiple tasks share a global counter variable. To avoid errors caused by simultaneous access, you need to protect the counter update using a critical section.
🎯 Goal: Build a simple FreeRTOS program that safely increments a shared counter variable inside a critical section using taskENTER_CRITICAL() and taskEXIT_CRITICAL().
📋 What You'll Learn
Create a global integer variable called counter initialized to 0
Create a variable called increment_value set to 5
Use taskENTER_CRITICAL() and taskEXIT_CRITICAL() to protect the increment operation on counter
Print the final value of counter after increment
💡 Why This Matters
🌍 Real World
In embedded systems, multiple tasks often share data. Using critical sections prevents data corruption when tasks run at the same time.
💼 Career
Understanding critical sections and FreeRTOS synchronization is essential for embedded software developers working on real-time applications.
Progress0 / 4 steps
1
Create the shared counter variable
Create a global integer variable called counter and set it to 0.
FreeRTOS
Hint
Use int counter = 0; to create the variable.
2
Create the increment value variable
Create an integer variable called increment_value and set it to 5.
FreeRTOS
Hint
Use int increment_value = 5; to create the variable.
3
Protect the increment with taskENTER_CRITICAL
Use taskENTER_CRITICAL() before incrementing counter by increment_value, and use taskEXIT_CRITICAL() after the increment.
FreeRTOS
Hint
Call taskENTER_CRITICAL(); before changing counter, and taskEXIT_CRITICAL(); after.
4
Print the final counter value
Write a printf statement to display the text "Counter value: " followed by the value of counter.
FreeRTOS
Hint
Use printf("Counter value: %d\n", counter); to print the value.
Practice
(1/5)
1. What is the main purpose of using taskENTER_CRITICAL() in FreeRTOS?
easy
A. To allocate memory dynamically
B. To disable interrupts and protect shared data during a critical section
C. To start a new task in the scheduler
D. To send a message to a queue
Solution
Step 1: Understand what taskENTER_CRITICAL() does
This function disables interrupts to prevent context switches and protect shared resources.
Step 2: Identify the purpose in multitasking
Disabling interrupts ensures that the critical section code runs without interruption, avoiding data corruption.
Final Answer:
To disable interrupts and protect shared data during a critical section -> Option B