0
0
FreeRTOSprogramming~7 mins

Tick timer and scheduler in FreeRTOS

Choose your learning style9 modes available
Introduction

The tick timer helps keep track of time in FreeRTOS. The scheduler uses this timer to decide which task to run next.

When you want to run multiple tasks smoothly on a microcontroller.
When you need tasks to run at specific time intervals.
When you want the system to switch tasks automatically without manual control.
When you want to save power by letting the CPU sleep between ticks.
When you want to manage task priorities and timing easily.
Syntax
FreeRTOS
void vTaskDelay(const TickType_t xTicksToDelay);

TickType_t xTaskGetTickCount(void);

vTaskDelay() pauses a task for a number of ticks.

xTaskGetTickCount() returns the current tick count since the scheduler started.

Examples
Delays the current task for 1000 milliseconds (1 second).
FreeRTOS
vTaskDelay(pdMS_TO_TICKS(1000));
Gets the current tick count value.
FreeRTOS
TickType_t ticks = xTaskGetTickCount();
Sample Program

This program creates two tasks. Task 1 prints a message every 500 milliseconds, and Task 2 prints every 1000 milliseconds. The scheduler uses the tick timer to switch between tasks automatically.

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

void vTask1(void *pvParameters) {
    for (;;) {
        printf("Task 1 running at tick %lu\n", xTaskGetTickCount());
        vTaskDelay(pdMS_TO_TICKS(500)); // Delay 500 ms
    }
}

void vTask2(void *pvParameters) {
    for (;;) {
        printf("Task 2 running at tick %lu\n", xTaskGetTickCount());
        vTaskDelay(pdMS_TO_TICKS(1000)); // Delay 1000 ms
    }
}

int main(void) {
    xTaskCreate(vTask1, "Task1", 1000, NULL, 1, NULL);
    xTaskCreate(vTask2, "Task2", 1000, NULL, 1, NULL);
    vTaskStartScheduler();
    for (;;) {}
    return 0;
}
OutputSuccess
Important Notes

The tick timer frequency is set in FreeRTOSConfig.h by configTICK_RATE_HZ.

Higher tick rates mean more precise timing but more CPU overhead.

The scheduler runs every tick to decide which task to run next based on priority and state.

Summary

The tick timer counts time in small steps called ticks.

The scheduler uses ticks to switch tasks smoothly and on time.

Use vTaskDelay() to pause tasks and xTaskGetTickCount() to check time.