0
0
FreeRTOSprogramming~5 mins

Idle task and idle hook in FreeRTOS

Choose your learning style9 modes available
Introduction

The idle task runs when no other tasks are ready to run. The idle hook lets you add your own code to run during this idle time.

You want to save power by putting the CPU to sleep when nothing else needs to run.
You want to perform background maintenance tasks without disturbing main tasks.
You want to monitor system health or statistics when the system is idle.
You want to clean up memory or resources during idle time.
Syntax
FreeRTOS
void vApplicationIdleHook(void) {
    // Your code here
}

The idle hook function must be named exactly vApplicationIdleHook.

You must enable the idle hook in FreeRTOSConfig.h by setting #define configUSE_IDLE_HOOK 1.

Examples
This example puts the CPU to sleep when idle to save power.
FreeRTOS
void vApplicationIdleHook(void) {
    // Put CPU to low power mode
    __WFI(); // Wait For Interrupt instruction
}
This example counts how many times the idle hook runs.
FreeRTOS
void vApplicationIdleHook(void) {
    // Increment a counter to track idle time
    idleCounter++;
}
Sample Program

This program creates one task that prints a message every second. The idle hook increments a counter whenever the system is idle.

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

volatile int idleCounter = 0;

void vApplicationIdleHook(void) {
    idleCounter++;
}

void vTaskFunction(void *pvParameters) {
    for (;;) {
        printf("Task running\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

int main(void) {
    xTaskCreate(vTaskFunction, "Task1", configMINIMAL_STACK_SIZE, NULL, 1, NULL);
    vTaskStartScheduler();
    // Scheduler should never return
    for (;;) {}
    return 0;
}
OutputSuccess
Important Notes

The idle task has the lowest priority and runs only when no other tasks are ready.

Do not block or call delay functions inside the idle hook; it must return quickly.

The idle hook is a good place for low priority background work or power saving.

Summary

The idle task runs when no other tasks are ready.

The idle hook lets you add code to run during idle time.

Enable the idle hook in FreeRTOSConfig.h and implement vApplicationIdleHook.