The user wants me to implement FreeRTOS tasks to manage multiple sensors with priority scheduling.
This means I need to provide C code that demonstrates:
- FreeRTOS setup: Including the necessary headers and configuration (conceptually, though I can't provide
FreeRTOSConfig.h).
- Task Creation: Defining multiple tasks, each representing a sensor handler.
- Priority Scheduling: Assigning different priorities to these tasks to show how preemptive scheduling works (high priority takes precedence over low priority).
- Sensor Simulation: Since I don't have real hardware, I need to mock the sensor reading process (e.g., using
vTaskDelay to simulate conversion time and random or dummy values).
- Resource Management (Optional but good): Using a Mutex to protect a shared resource like the UART (printf) so output doesn't get garbled.
- Structure: A clear, compilable (with an embedded target) main file structure.
Step 1: Define the Scenario
Let's pick three distinct sensors to make it realistic:
- Sensor A (Urgent): Smoke Detector or Emergency Stop. Needs high priority. Fast execution, frequent checks.
- Sensor B (Periodic): Temperature/Humidity. Medium priority. Slower execution, less frequent checks.
- Sensor C (Background): Battery Level or Log dump. Low priority. Very infrequent checks.
Step 2: Code Structure
- Includes:
FreeRTOS.h, task.h, queue.h, semphr.h.
- Macros: Priorities, stack sizes.
- Shared Resources: A Mutex for serial output.
- Task Functions:
vHighPriorityTask: Simulate reading a critical sensor. Use a short delay.
vMediumPriorityTask: Simulate reading a standard sensor. Use a medium delay.
vLowPriorityTask: Simulate a background task.
main(): Initialize hardware (mocked), create Mutex, create Tasks, start Scheduler.
Step 3: Drafting the Code (Mental or Scratchpad)
- Priorities: FreeRTOS allows numeric priorities. Usually, higher number = higher priority (configurable, but standard assumption). Let's use 3 (High), 2 (Medium), 1 (Low).
- Synchronization: If all tasks try to print at once, the console output will be interleaved and unreadable. A Mutex (
xSemaphore) is essential. I need a wrapper function safe_printf or similar logic.
Step 4: Refining the "Sensor" Logic
- Critical Sensor: Maybe it reads every 100ms.
- Standard Sensor: Reads every 500ms.
- Background Sensor: Reads every 2000ms.
- Simulating Work:
vTaskDelay blocks the task, allowing the scheduler to switch contexts. This demonstrates the priority. If the High priority task is ready, it interrupts the Low priority task.
Step 5: Adding Complexity (Inter-Task Communication)
To make it a real sensor management system, I should probably use a Queue.
- Idea: Tasks read sensors, then send data to a "Processing" or "Logger" task via a Queue.
- Decision: While a Queue is excellent, the prompt specifically asks for "priority scheduling." Demonstrating preemption is easier to see in code comments and logic if the tasks run independently with different frequencies. However, a Queue system is cleaner architecture.
- Compromise: I will keep the tasks independent for clarity on priority (showing how high priority takes CPU time), but I will add a Mutex to demonstrate shared resource protection, which is crucial in sensor networks. I will also include a simple "Data Processing" simulation within the tasks.
Step 6: Writing the Code (Iterative refinement)
Step 7: Adding Context and Explanation
The code alone isn't enough. I need to explain:
- Priorities: How
tskIDLE_PRIORITY + x works.
- Preemption: How the scheduler pauses lower tasks.
- Blocking:
vTaskDelay puts tasks to sleep so others can run.
- Mutual Exclusion: Why the Mutex is there.
Self-Correction/Review during drafting:
- Code complexity: Keep it generic. Don't use STM32 HAL or ESP-IDF specific code. Use standard
printf and assume vTaskDelay works.
- Stack size: Use a macro
configMINIMAL_STACK_SIZE generally, but maybe define specific words (e.g., 128, 256).
- Output: The user needs to see the result. I will describe what the output looks like.
Final Plan:
- Introduction: Briefly explain the architecture (3 sensors, 3 priorities).
- The Code:
- Define Priorities.
- Create a Mutex for Serial Output (Critical for debugging).
vTask_Sensor_Ultrasonic (High Priority): Fast polling.
vTask_Sensor_Temp (Medium Priority): Slower polling.
vTask_Sensor_Battery (Low Priority): Very slow polling.
main: Setup and launch.
- Key Concepts: Break down Priority, Blocking, and Mutex.
- Build Instructions: Mention the need for a toolchain (STM32CubeIDE, ESP-IDF, etc.).
This looks solid. I will generate the C code now. I will ensure the Mutex handling is robust (checking return values).
Let's write the specific code segments.
- High Priority:
tskIDLE_PRIORITY + 3
- Medium:
tskIDLE_PRIORITY + 2
- Low:
tskIDLE_PRIORITY + 1
The code should simulate reading values. I'll use rand() for values.
Check: Did the user ask for inter-task communication? "Manage multiple sensors." Not explicitly. Independent tasks are the simplest implementation of priority scheduling.
Check: Did the user specify a MCU? No. Generic C code is best.
Let's go.
Here is a complete implementation framework using FreeRTOS to manage multiple sensors with priority scheduling.
This example demonstrates a classic Priority Preemptive scheduling scenario:
- High Priority: A critical sensor (e.g., Smoke Detector) that must react immediately.
- Medium Priority: A standard sensor (e.g., Temperature/Humidity) that polls periodically.
- Low Priority: A background task (e.g., Data Logging) that runs when the CPU is idle.
1. The C Implementation
This code is generic. It can run on STM32, ESP32, or Arduino (with FreeRTOS enabled), provided you have the standard FreeRTOS headers.
/*
* FreeRTOS Sensor Management Example
*
* Architecture:
* 1. Critical Task (High Priority): Simulates an interrupt-driven or fast-polling sensor.
* 2. Periodic Task (Medium Priority): Standard environmental monitoring.
* 3. Background Task (Low Priority): Non-critical data aggregation.
*/
#include <stdio.h>
#include <stdlib.h>
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h" // For Mutexes
/* ------------------ Configuration ------------------ */
// Priorities (Higher number = Higher Priority)
#define PRIORITY_CRITICAL ( 3 )
#define PRIORITY_STANDARD ( 2 )
#define PRIORITY_BACKGROUND ( 1 )
// Stack Sizes (words, not bytes)
#define STACK_SIZE_MIN ( 128 )
#define STACK_SIZE_STANDARD ( 256 )
// Simulated Sensor Ports
#define TEMP_SENSOR_ID 1
#define PRESSURE_SENSOR_ID 2
/* ------------------ Global Resources ------------------ */
// Mutex to protect the Serial Port (UART/USB) output
// Without this, text from different tasks would get garbled.
SemaphoreHandle_t xSerialMutex;
/* ------------------ Helper Functions ------------------ */
// Simulate reading hardware
int read_hardware(int sensor_id) {
return (rand() % 100); // Return random value between 0-99
}
// Thread-safe print function
void safe_print(const char *format, ...) {
char buffer[128];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
// Attempt to take the mutex (wait max 100 ticks)
if( xSemaphoreTake( xSerialMutex, ( TickType_t ) 100 ) == pdTRUE ) {
printf(buffer); // Write to UART/Console
xSemaphoreGive( xSerialMutex ); // Release mutex
}
}
/* ------------------ Task Definitions ------------------ */
/*
* TASK 1: Smoke/Critical Sensor
* Priority: HIGH (3)
* Behavior: Fast polling. Preempts all other tasks.
*/
void vTask_CriticalSensor(void *pvParameters) {
TickType_t xLastWakeTime = xTaskGetTickCount();
const TickType_t xFrequency = pdMS_TO_TICKS(50); // Run every 50ms
safe_print("[CRITICAL] Task Started.\n");
while (1) {
// 1. Read Sensor
int value = read_hardware(0);
// 2. Check Thresholds (Simulated)
if (value > 90) {
safe_print("[ALERT!] Critical Sensor Triggered! Val: %d\n", value);
}
// 3. Block until next cycle
// This allows lower priority tasks to run briefly
vTaskDelayUntil(&xLastWakeTime, xFrequency);
}
}
/*
* TASK 2: Temperature Monitor
* Priority: MEDIUM (2)
* Behavior: Standard polling.
*/
void vTask_TempSensor(void *pvParameters) {
TickType_t xLastWakeTime = xTaskGetTickCount();
const TickType_t xFrequency = pdMS_TO_TICKS(500); // Run every 500ms
safe_print("[TEMP] Task Started.\n");
while (1) {
int temp = read_hardware(TEMP_SENSOR_ID);
// Simulate processing time (calculations, I2C comms)
// This task can be preempted by CRITICAL task during this delay
safe_print("[TEMP] Reading: %d C\n", temp);
// Block until exact interval
vTaskDelayUntil(&xLastWakeTime, xFrequency);
}
}
/*
* TASK 3: Data Logger
* Priority: LOW (1)
* Behavior: Background processing. Only runs when High/Medium tasks are sleeping.
*/
void vTask_DataLogger(void *pvParameters) {
safe_print("[LOGGER] Background Task Started.\n");
while (1) {
// This task demonstrates the Idle state.
// It runs continuously unless preempted by higher priority tasks.
safe_print("[LOGGER] Saving data to SD card...\n");
// Simulate a long write process
// We use a short delay here to yield CPU, allowing the scheduler to check higher prio tasks
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
/* ------------------ Main Entry Point ------------------ */
int main(void) {
// Initialize Hardware (UART, Sensors, etc.)
// hardware_init();
// Create the Mutex for Serial Communication
xSerialMutex = xSemaphoreCreateMutex();
if (xSerialMutex != NULL) {
// Create Tasks
xTaskCreate(vTask_CriticalSensor, "Crit_Sensor", STACK_SIZE_MIN, NULL, PRIORITY_CRITICAL, NULL);
xTaskCreate(vTask_TempSensor, "Temp_Sensor", STACK_SIZE_STANDARD, NULL, PRIORITY_STANDARD, NULL);
xTaskCreate(vTask_DataLogger, "Logger", STACK_SIZE_MIN, NULL, PRIORITY_BACKGROUND, NULL);
// Start the Scheduler
// This function never returns
vTaskStartScheduler();
}
// Should never reach here
for( ;; );
}
2. Explanation of Key Concepts
Priority Scheduling
FreeRTOS uses a Fixed Priority Preemptive system.
- Fixed Priority: The priority we assign in
xTaskCreate does not change unless we manually change it (or use Mutexes with Priority Inheritance).
- Preemptive: If the
CRITICAL task is ready to run (e.g., its delay expires), it will immediately pause (preempt) the LOGGER or TEMP task, even if they are in the middle of execution.
The Timing Diagram
Imagine the system is running the LOGGER task (Low Priority).
- Time 0ms:
LOGGER is printing "Saving data...".
- Time 50ms: The
CRITICAL task delay expires. The Scheduler Preempts LOGGER, switches context to CRITICAL, runs it, and CRITICAL goes back to sleep.
- Time 51ms: Scheduler switches back to
LOGGER to finish its work.
- Time 500ms:
TEMP task wakes up. It preempts LOGGER.
Blocking (vTaskDelayUntil)
We use vTaskDelayUntil instead of a busy-wait while loop.
- Wrong:
while(true) { read(); sleep(100); } (Keeps CPU awake, wastes power).
- Right:
vTaskDelayUntil puts the task into the Blocked state. In this state, the task consumes zero CPU cycles. This allows the Microcontroller to enter low-power modes or execute other tasks.
Mutual Exclusion (Mutex)
Because printf (sending data to the serial port) is not an atomic operation, it is a Shared Resource.
- If the High Priority task interrupts the Low Priority task while the Low task is printing a sentence, you would get garbage output mixed from both tasks (e.g.,
Saving d[ALERT!] Criticalata...).
- The
xSerialMutex ensures that only one task can print at a time.
3. Best Practices for Sensor Tasks
- Keep ISRs Short: If your sensor has a hardware interrupt (like a Data Ready pin), keep the Interrupt Service Routine (ISR) extremely short. Use
xQueueSendFromISR to send data to a task for processing.
- Stack Overflow Protection: Ensure you enable
configCHECK_FOR_STACK_OVERFLOW in FreeRTOSConfig.h. Sensors often use library functions that consume more stack than you expect.
- Avoid Starvation: In this example, the
CRITICAL task runs every 50ms. If it took 40ms to execute, the LOGGER task would only get 20% of the CPU time. Ensure your high-priority tasks execute quickly and block often.