Skip to content
systemcoding.dev
RTOS

The Complete Guide to FreeRTOS Software Timers and Tickless Idle

Learn FreeRTOS V11.1.0 software timers, the timer service task, the idle hook and tickless idle, from one-shot timers to low-power setup.

27 min read
Summarize in AI
Flat illustration of RTOS tasks taking turns on a timeline, with the C, Rust and Arm logos.

A firmware that blinks an LED, times out a lost packet and goes to sleep between events needs three things from its RTOS: a way to run a function after a delay without dedicating a task to it, a place to do background work when nothing else is ready, and a way to stop the periodic tick interrupt from waking the processor a thousand times a second for nothing. FreeRTOS provides exactly those three: software timers, the idle task with its hook, and tickless idle. This guide covers all three on FreeRTOS kernel V11.1.0 with a Cortex-M4 and arm-none-eabi-gcc 13.2, from the first one-shot timer to the configuration that lets a battery-powered device sleep through its idle time. Every section has code, and every program that prints has its output.

The short version: a software timer is a callback the kernel runs for you, in a single shared task, after a period you choose. Keep callbacks short and never block in them. The idle hook is a function the idle task calls each time it runs, and tickless idle replaces the tick interrupt with one long sleep when every task is blocked for a while. Used together, they cover most of what a low-power embedded application needs from time.

If your timing need is a task that does something every 100 ms with its own stack and state, a task with vTaskDelayUntil() is a better fit, as the periodic task post compares. This guide is about the cases where a callback is the right size.

What a software timer is

A software timer calls a function of your choice when a period expires. It is called a software timer because it uses no hardware timer peripheral of its own: the kernel keeps a list of timers sorted by expiry, and a single task, the timer service task (also called the timer daemon, and named "Tmr Svc" in task lists), sleeps until the earliest expiry and then runs the callback.

Two modes exist:

ModeBehaviorCreated with
One-shotRuns its callback once after the period, then stops, and can be started againxAutoReload set to pdFALSE
Auto-reloadRuns its callback every period until stoppedxAutoReload set to pdTRUE

Because all callbacks run in the same task, timers share its stack and its priority, and a callback that takes long delays every other timer. That one fact explains most of the rules in this guide.

Configuration

Timers are off by default. In FreeRTOSConfig.h:

FreeRTOSConfig.hc
#define configUSE_TIMERS                1
#define configTIMER_TASK_PRIORITY       ( configMAX_PRIORITIES - 2 )
#define configTIMER_QUEUE_LENGTH        10
#define configTIMER_TASK_STACK_DEPTH    ( configMINIMAL_STACK_SIZE * 2 )

configUSE_TIMERS makes vTaskStartScheduler() create the timer service task. configTIMER_TASK_PRIORITY is the priority that all callbacks run at, so choose it with the callbacks' urgency in mind: a high priority gives timely callbacks and lets them preempt your application tasks, while a low one makes them wait. configTIMER_QUEUE_LENGTH is the capacity of the command queue that carries every start, stop, reset and period change from your code to the timer task. configTIMER_TASK_STACK_DEPTH is in words, not bytes, and must cover the deepest callback.

Also add the source: timers.c must be in your build, and your code includes timers.h.

Your first timers

timers_basic.cc
#include <stdio.h>
#include "FreeRTOS.h"
#include "timers.h"
#include "task.h"

static void blink_callback(TimerHandle_t xTimer)
{
    (void)xTimer;
    printf("[%lu] blink\n", (unsigned long)xTaskGetTickCount());
}

static void timeout_callback(TimerHandle_t xTimer)
{
    (void)xTimer;
    printf("[%lu] timeout fired once\n", (unsigned long)xTaskGetTickCount());
}

int main(void)
{
    TimerHandle_t blink = xTimerCreate("blink", pdMS_TO_TICKS(200), pdTRUE, NULL, blink_callback);
    TimerHandle_t once  = xTimerCreate("once",  pdMS_TO_TICKS(500), pdFALSE, NULL, timeout_callback);

    configASSERT(blink != NULL && once != NULL);

    xTimerStart(blink, 0);
    xTimerStart(once, 0);

    vTaskStartScheduler();
    for (;;) { }
}
Text
[200] blink
[400] blink
[500] timeout fired once
[600] blink
[800] blink
[1000] blink

This assumes configTICK_RATE_HZ of 1,000. The auto-reload blink timer fires every 200 ms forever. The one-shot once fires at 500 ms and never again.

The arguments of xTimerCreate(name, period, autoReload, id, callback) are: a name used only for debugging, the period in ticks (it must be greater than zero), whether to reload, an opaque void * identifier you can read back inside the callback, and the callback function. It returns NULL if the heap cannot supply the timer's control block, so the assert after it is not decoration.

Two points trip beginners. First, xTimerCreate() creates the timer dormant; nothing happens until you start it. Second, xTimerStart() before the scheduler runs just records the timer; the clock starts at scheduler start, which is why the output above is measured from tick 0.

The second argument of xTimerStart(timer, ticksToWait) is a block time, and it needs explaining. Timer commands travel through a queue to the timer task. If the queue is full, xTimerStart() can wait up to ticksToWait for space. Called before the scheduler starts, the block time is ignored. In a callback, never use a nonzero block time, because a callback that blocks stalls the timer task, which is the task that would drain the queue.

The post on creating timers works through creation and the return values in more detail.

How the timer service task works

Understanding the machinery removes most of the surprises. The timer service task runs a loop with two jobs:

  1. Process commands. Calls such as xTimerStart(), xTimerStop(), xTimerReset() and xTimerChangePeriod() do not touch the timer lists themselves. They send a command, with the tick count at the moment of the call, to the timer queue and return. The timer task takes commands from the queue and applies them.

  2. Run expired timers. The timer task keeps two lists sorted by expiry time, one for the current tick-counter epoch and one for after the counter overflows. When the head timer's time arrives, it removes the timer, runs its callback and, for an auto-reload timer, computes the next expiry and re-inserts it.

When there is nothing to do, the task blocks on the command queue with a timeout equal to the time until the next expiry. A command wakes it early; the timeout wakes it for an expiry. The explainer on the timer service task walks through this loop.

Three consequences follow.

Commands are time-stamped when sent, not when processed. If you call xTimerStart() at tick 1,000 but the timer task is delayed by a higher-priority task until tick 1,030, the timer's expiry is still computed from tick 1,000. A 200-tick timer fires at 1,200, and the delay in processing the command does not shift it.

A callback is late if the timer task is. If a higher-priority task keeps the processor, the timer task cannot run, and the callback runs when it can. The expiry time is a lower bound on when the callback starts, not an exact moment.

Auto-reload timers do not drift. The next expiry is computed from the previous expiry time, not from when the callback finished, so a callback that runs late does not push later callbacks back. If the timer task misses a whole period, the kernel runs the callback once per missed expiry as it catches up, with no delay between them.

One callback, several timers: the timer ID

A single function can serve many timers if it can tell which one fired. The timer ID, set at creation, is the tool, and pvTimerGetTimerID() reads it inside the callback.

timer_id.cc
#include <stdio.h>
#include "FreeRTOS.h"
#include "timers.h"
#include "task.h"

typedef struct {
    const char *name;
    uint32_t    fired;
} channel_t;

static channel_t s_ch[3] = { { "ch0", 0 }, { "ch1", 0 }, { "ch2", 0 } };

static void channel_callback(TimerHandle_t xTimer)
{
    channel_t *c = pvTimerGetTimerID(xTimer);
    c->fired++;
    printf("[%lu] %s fired (%lu)\n", (unsigned long)xTaskGetTickCount(),
           c->name, (unsigned long)c->fired);
}

void channels_start(void)
{
    const TickType_t periods[3] = { pdMS_TO_TICKS(100), pdMS_TO_TICKS(250), pdMS_TO_TICKS(250) };

    for (int i = 0; i < 3; i++) {
        TimerHandle_t t = xTimerCreate(s_ch[i].name, periods[i], pdTRUE, &s_ch[i], channel_callback);
        configASSERT(t != NULL);
        xTimerStart(t, 0);
    }
}
Text
[100] ch0 fired (1)
[200] ch0 fired (2)
[250] ch1 fired (1)
[250] ch2 fired (1)
[300] ch0 fired (3)

The ID is a void *, so it can be a pointer to a per-timer structure, as here, or a small integer cast to a pointer. A structure is the better choice because it carries state without globals. The order of ch1 and ch2 at tick 250 is the order in which their expiries were inserted into the timer list, which for equal expiry times follows the order they were started.

Changing a running timer

Four calls change a timer's state, and each one is a command to the timer task:

CallEffect
xTimerStop(t, block)Stops the timer; it keeps its period and can be started again
xTimerReset(t, block)Restarts the period from now, and starts a stopped timer
xTimerChangePeriod(t, newPeriod, block)Sets a new period, restarts the timer from now, and starts a dormant timer
xTimerDelete(t, block)Removes the timer; the handle is invalid afterwards

xTimerReset() is the basis of the watchdog-style timeout, covered in its own post: a timer that is reset every time a heartbeat arrives never expires, and one that stops receiving heartbeats fires. xTimerChangePeriod() is how you retune an interval at run time, as the period-change post shows.

retune.cc
#include <stdio.h>

static TimerHandle_t s_poll;

static void poll_callback(TimerHandle_t t)
{
    (void)t;
    printf("[%lu] poll\n", (unsigned long)xTaskGetTickCount());
}

void retune_demo(void)
{
    s_poll = xTimerCreate("poll", pdMS_TO_TICKS(100), pdTRUE, NULL, poll_callback);
    xTimerStart(s_poll, 0);
}

void on_user_slows_polling(void)           /* called from a task at about tick 250 */
{
    xTimerChangePeriod(s_poll, pdMS_TO_TICKS(400), pdMS_TO_TICKS(10));
}
Text
[100] poll
[200] poll
[650] poll
[1050] poll

The change at tick 250 restarts the timer with a 400-tick period from that moment, so the next callback is at 650, not at 300. If you want the old phase kept, compute the next expiry yourself and use xTimerGetExpiryTime(). The block time of 10 ms in the call is how long the caller will wait for room in the command queue.

The return values matter and are easy to ignore: xTimerStart(), xTimerStop(), xTimerReset() and xTimerChangePeriod() return pdPASS if the command was queued and pdFAIL if the queue was full for the whole block time. A pdFAIL means the command was dropped, and the timer's state is not what you intended. Check it for anything that matters.

Timers from an interrupt

An interrupt can send the same commands with xTimerStartFromISR(), xTimerStopFromISR(), xTimerResetFromISR() and xTimerChangePeriodFromISR(). They take a woken pointer like every FromISR call, and end with portYIELD_FROM_ISR():

timer_isr.cc
void EXTI9_5_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    EXTI->PR = EXTI_PR_PR6;
    xTimerResetFromISR(s_idleTimer, &woken);       /* the button was touched: restart the countdown */
    portYIELD_FROM_ISR(woken);
}

An interrupt that wants to run its own function at task level uses xTimerPendFunctionCallFromISR(), which queues a function pointer and two arguments for the timer task:

pend.cc
static void deferred_work(void *param1, uint32_t param2)
{
    printf("deferred: id=%lu value=%lu\n", (unsigned long)(uintptr_t)param1, (unsigned long)param2);
}

void SPI1_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    uint32_t status = SPI1->SR;
    SPI1->SR = 0;
    xTimerPendFunctionCallFromISR(deferred_work, (void *)(uintptr_t)1, status, &woken);
    portYIELD_FROM_ISR(woken);
}
Text
deferred: id=1 value=1

This needs INCLUDE_xTimerPendFunctionCall set to 1. The function runs in the timer service task, so it must obey the same no-blocking rule as a callback. It is a convenient way to move ISR work to task level without creating a task and a queue, and the pend-function post covers the failure modes: a full command queue returns pdFAIL and the work is dropped.

Running a function from a task in the timer service context

The pend-function call has a task-level twin, xTimerPendFunctionCall(), which a task can use to ask the timer service task to run a function for it, with a block time for the command queue:

pend_task.cc
static void flush_log(void *param1, uint32_t param2)
{
    (void)param1;
    printf("flush %lu bytes\n", (unsigned long)param2);
    log_flush_to_flash(param2);
}

void request_flush(uint32_t bytes)
{
    if (xTimerPendFunctionCall(flush_log, NULL, bytes, pdMS_TO_TICKS(10)) != pdPASS) {
        s_flushRequestsDropped++;
    }
}
Text
flush 128 bytes

Use it for a small amount of work that should happen outside the caller's context and priority, such as shifting a flash write off a time-critical task. Because the function runs in the timer service task, it follows the callback rules: it must not block, and a flash write that takes milliseconds delays every timer. For long work, have the function notify a task instead. A full command queue returns pdFAIL, as with any timer command, so check it.

The rules for callbacks

Callbacks run in the timer service task, which is shared with every other timer and with the pended functions. Five rules follow, and breaking any of them causes bugs far from the callback:

  1. Never block. No vTaskDelay(), no xQueueReceive() with a timeout, no xSemaphoreTake() with a timeout, and no use of xTimerStart() with a block time. A callback that blocks stops every timer in the system.

  2. Keep it short. The callback delays every timer behind it. A callback that takes 5 ms makes all timers up to 5 ms late.

  3. Do not delete the timer you are running in without care. Deleting from the callback is allowed through the command queue, but the handle is dangling afterwards.

  4. Size the stack for the deepest callback. printf() in a callback can need a large stack; the timer task's stack is configTIMER_TASK_STACK_DEPTH words.

  5. Pass work on instead of doing it. If the work is long, have the callback notify a task or send to a queue, using non-blocking calls with a zero timeout, and let the task do the work.

callback_handoff.cc
static TaskHandle_t s_workerTask;

static void sample_timer_cb(TimerHandle_t t)
{
    (void)t;
    xTaskNotifyGive(s_workerTask);             /* returns immediately, never blocks */
}

static void worker_task(void *arg)
{
    (void)arg;
    for (;;) {
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
        read_sensor_and_filter();               /* long work, in a normal task */
    }
}

The timer provides the beat, the task does the work, and the timer task is free again the moment the notification is queued. This is the shape of most real timer use.

Static allocation

With configSUPPORT_STATIC_ALLOCATION set to 1, create a timer in memory you provide:

timer_static.cc
static StaticTimer_t s_blinkBuf;
static TimerHandle_t s_blink;

void blink_init(void)
{
    s_blink = xTimerCreateStatic("blink", pdMS_TO_TICKS(200), pdTRUE, NULL,
                                 blink_callback, &s_blinkBuf);
    configASSERT(s_blink != NULL);
}

With static allocation you must also supply the memory of the timer service task itself, by defining vApplicationGetTimerTaskMemory():

timer_task_mem.cc
void vApplicationGetTimerTaskMemory(StaticTask_t **ppxTimerTaskTCBBuffer,
                                    StackType_t **ppxTimerTaskStackBuffer,
                                    configSTACK_DEPTH_TYPE *puxTimerTaskStackSize)
{
    static StaticTask_t timerTCB;
    static StackType_t  timerStack[configTIMER_TASK_STACK_DEPTH];

    *ppxTimerTaskTCBBuffer   = &timerTCB;
    *ppxTimerTaskStackBuffer = timerStack;
    *puxTimerTaskStackSize   = configTIMER_TASK_STACK_DEPTH;
}

Forgetting this function produces a link error that mentions it by name, which is easy to recognize.

The idle task and the idle hook

When every other task is blocked or suspended, the scheduler still needs something to run. That is the idle task, created automatically by vTaskStartScheduler() at the lowest priority, tskIDLE_PRIORITY (0). It has two jobs: free the memory of deleted tasks, and run your idle hook if you enabled one.

The hook is a function you define, called once per iteration of the idle loop:

FreeRTOSConfig.hc
#define configUSE_IDLE_HOOK 1
idle_hook.cc
static volatile uint32_t s_idleCount;

void vApplicationIdleHook(void)
{
    s_idleCount++;
    __WFI();                                    /* sleep until the next interrupt */
}

__WFI() is the CMSIS intrinsic for the Cortex-M WFI instruction, "wait for interrupt": the core sleeps until any interrupt arrives, including the tick. Even this simple hook saves power compared with a busy idle loop, though the tick still wakes the core 1,000 times a second, which tickless idle removes.

The hook has three rules. It must never block or suspend, because the idle task must always be ready to run, and a blocked idle task leaves the scheduler with nothing to schedule. It must return regularly, because the idle task does its memory cleanup between calls. And it should be short, since any work in the hook delays the idle task's housekeeping and the transition into low power.

Use the hook for low-priority background work that can be done in small pieces: a CRC pass over flash, a statistics update, a scrub of a memory region, or kicking a watchdog when the system is otherwise healthy. The idle hook post shows a worked example, and notes the alternatives, a low-priority task and a software timer.

The idle count also gives a crude load measure. The hook runs more often when the system is less busy, so a count compared with its peak under no load gives an idea of spare capacity. The kernel's run-time statistics, described in the CPU usage post, do it properly.

Tickless idle

By default the kernel keeps a periodic tick interrupt, normally SysTick on a Cortex-M, at configTICK_RATE_HZ. At 1,000 Hz it fires every millisecond, and each firing wakes a sleeping core, runs the tick handler and returns. When the system is idle for seconds at a time, those wake-ups waste energy for no purpose, since nothing was due.

Tickless idle stops the tick when the idle task knows that every task is blocked for at least some number of ticks. It programs a wake-up timer for the time of the next event, puts the core to sleep, and when the processor wakes, whether by that timer or by another interrupt, it advances the kernel's tick count by the time that passed. The tick count stays correct, and the processor slept through the quiet time without interruptions.

Enable it with:

FreeRTOSConfig.hc
#define configUSE_TICKLESS_IDLE                  1
#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP    10

configEXPECTED_IDLE_TIME_BEFORE_SLEEP is the smallest idle period, in ticks, for which the kernel will bother to stop the tick. The default is 2, and it cannot be lower than 2. A larger value avoids the cost of stopping and restarting the tick for short idle gaps: if switching in and out of sleep takes longer than the gap, you waste energy. Pick it from the wake-up latency and cost of your sleep mode.

With configUSE_TICKLESS_IDLE set to 1, the Cortex-M ports provide a default implementation, vPortSuppressTicksAndSleep(), that uses SysTick as the wake-up timer and the WFI instruction as the sleep. It works for sleep modes that keep SysTick running, which is the shallow sleep of most Cortex-M parts. For deeper sleep modes that stop SysTick, you supply your own implementation, using a low-power timer that keeps running, by defining portSUPPRESS_TICKS_AND_SLEEP() in FreeRTOSConfig.h.

How the idle task decides to sleep

The decision lives in the idle task's loop in tasks.c, and reading it once removes the mystery from tickless idle. Each pass of the loop does the following, in order:

  1. It frees the memory of any tasks that were deleted since the last pass.

  2. If time slicing is on and other tasks share the idle priority, it yields to them.

  3. It calls your idle hook, if configUSE_IDLE_HOOK is 1.

  4. If configUSE_TICKLESS_IDLE is 1, it asks the kernel how long the system can be idle. The answer, the expected idle time, is the number of ticks until the earliest task is due to unblock, which includes the timer service task's next wake-up.

  5. If that time is greater than configEXPECTED_IDLE_TIME_BEFORE_SLEEP, it suspends the scheduler, recomputes the time to make sure nothing changed, and asks eTaskConfirmSleepModeStatus() whether sleeping is allowed.

  6. If the answer is eAbortSleep, because a task became ready or a yield is pending, it skips the sleep. Otherwise it calls portSUPPRESS_TICKS_AND_SLEEP() with the expected idle time, and then resumes the scheduler.

Two consequences are worth keeping in mind. The hook runs on every pass, including the passes that go on to sleep, so it runs before the sleep and should not try to sleep itself if tickless idle is on, or it will sleep twice. And the sleep decision is re-checked with the scheduler suspended, which closes the race in which an interrupt readies a task between the first calculation and the sleep. If an interrupt fires in that window, the kernel notes a pending ready task, and eTaskConfirmSleepModeStatus() returns eAbortSleep, so the system does not oversleep.

The function can also return a mode that says no task has any timeout at all. When every task is blocked indefinitely (and INCLUDE_vTaskSuspend is 1), the expected idle time becomes the maximum the port can represent, and the port may sleep for the longest period its timer allows, waking only for an external interrupt. That is the state of a device that waits for a button press and does nothing else.

Hooks around the sleep

Two macros let you prepare the hardware before sleeping and restore it after:

FreeRTOSConfig.hc
#define configPRE_SLEEP_PROCESSING(x)   app_pre_sleep(&(x))
#define configPOST_SLEEP_PROCESSING(x)  app_post_sleep(x)
sleep_hooks.cc
#include <stdio.h>

static volatile uint32_t s_sleeps;

void app_pre_sleep(TickType_t *xExpectedIdleTime)
{
    (void)xExpectedIdleTime;
    s_sleeps++;
    gpio_set_all_pins_low_power();           /* park unused pins */
    peripheral_clocks_gate_off();             /* stop clocks nobody needs */
    /* Leaving *xExpectedIdleTime non-zero lets the port do the WFI itself. */
}

void app_post_sleep(TickType_t xExpectedIdleTime)
{
    (void)xExpectedIdleTime;
    peripheral_clocks_restore();
    gpio_restore_pins();
}

The pre-sleep macro receives the expected idle time by reference, so it can set it to zero to tell the port that the hook already put the processor to sleep, for a custom deep-sleep path. The post-sleep macro runs after the wake-up. Both run with interrupts masked inside the port's sleep sequence, so keep them quick.

A run on a device with a 300 ms gap between two events shows tickless idle at work. We count the tick interrupts using the tick hook:

tick_count.cc
#define configUSE_TICK_HOOK 1

static volatile uint32_t s_ticks;

void vApplicationTickHook(void)
{
    s_ticks++;
}

static void report_task(void *arg)
{
    (void)arg;
    for (;;) {
        uint32_t before = s_ticks;
        vTaskDelay(pdMS_TO_TICKS(300));
        printf("[%lu] tick interrupts during the 300 ms delay: %lu\n",
               (unsigned long)xTaskGetTickCount(), (unsigned long)(s_ticks - before));
    }
}

With tickless idle off, the tick hook runs on every tick:

Text
[300] tick interrupts during the 300 ms delay: 300
[600] tick interrupts during the 300 ms delay: 300

With tickless idle on, the processor sleeps through the gap, and the tick hook runs only for the few ticks when the processor is awake around the sleep, so the count is a small number instead of 300. The exact small number depends on your sleep implementation and port, and the point of the measurement is the large reduction, not the figure. The tick count itself, printed from xTaskGetTickCount(), still advances by 300, because the kernel adds the slept ticks when it wakes.

What tickless idle does to timers

The timer service task is a task like any other: when it has no expiry for a while, it blocks with a long timeout. The idle task's calculation of how long it can sleep considers every task's next unblock time, including the timer task's. So an auto-reload timer with a 5-second period lets the processor sleep for nearly 5 seconds at a time, waking for the expiry. A timer with a 10 ms period prevents any deep sleep, since the gap between expiries is shorter than configEXPECTED_IDLE_TIME_BEFORE_SLEEP plus the wake-up cost. Review your timer periods when you turn tickless idle on: a forgotten 20 ms housekeeping timer can cost more power than all the rest of the design.

Things that go wrong with tickless idle

Another interrupt keeps waking the core. Any interrupt that fires during the sleep ends it early, and the kernel recomputes the tick count from the elapsed time. A noisy sensor interrupt, a floating GPIO or a debug UART defeats the saving. Find the wake source with the debugger's interrupt trace.

The tick count is wrong after waking. The port measures the slept time with the wake-up timer. If that timer stops in the sleep mode you use (for example SysTick in a deep sleep), the elapsed time is lost, and the tick count falls behind, which breaks every timeout. Use a timer that runs in your sleep mode.

The debugger prevents sleep. An attached debug probe often keeps the core clock and debug logic powered, so the measured current looks the same with or without tickless idle. Measure with the probe disconnected.

A vendor HAL uses SysTick for its own time base. The STM32 HAL uses SysTick for HAL_GetTick() by default, which collides with FreeRTOS's use of SysTick. The fix is to move the HAL time base to a spare timer, as the HAL time-base post shows. Tickless idle makes the collision worse, since stopping SysTick would stop the HAL's tick.

Pre-sleep hooks that take too long. Gating clocks and parking pins costs time on every sleep. If the gap is short, the hooks cost more than they save, which is another reason to set configEXPECTED_IDLE_TIME_BEFORE_SLEEP generously.

Tasks that poll. A task that wakes every millisecond with vTaskDelay(1) never lets the system idle. Replace polling with blocking on an event.

Accuracy, drift and tick overflow

Three properties of time in the kernel decide how far you can trust a timer.

Resolution is one tick. Timer periods are whole ticks, and pdMS_TO_TICKS() truncates. At a tick rate of 100 Hz, pdMS_TO_TICKS(25) is 2 ticks, which is 20 ms, and pdMS_TO_TICKS(5) is 0 ticks, which is an invalid timer period and asserts. Choose a tick rate so that your shortest period is several ticks long, since a period of N ticks fires between N-1 and N ticks after the start command, depending on where in a tick the call landed.

Auto-reload timers keep their phase. The kernel computes the next expiry as the previous expiry plus the period, not as the time the callback ended. A callback that runs 3 ticks late does not push the next one by 3 ticks. A task loop written with vTaskDelay(period) drifts, because each iteration adds its own run time to the period; vTaskDelayUntil() and auto-reload timers do not.

drift.cc
static void drifting_task(void *arg)
{
    (void)arg;
    for (;;) {
        do_work();                                  /* takes a few ticks */
        vTaskDelay(pdMS_TO_TICKS(100));             /* period is 100 ms + work time */
    }
}

static void steady_task(void *arg)
{
    (void)arg;
    TickType_t last = xTaskGetTickCount();
    for (;;) {
        do_work();
        vTaskDelayUntil(&last, pdMS_TO_TICKS(100)); /* period is exactly 100 ms */
    }
}

If do_work() takes 7 ticks, drifting_task runs every 107 ticks and steady_task every 100. A timer with a 100-tick period behaves like steady_task.

The tick counter wraps. TickType_t is 32 bits unless configUSE_16_BIT_TICKS is 1, so at 1,000 Hz the counter wraps after about 49.7 days. With 16-bit ticks it wraps in about 65 seconds, which is why 16-bit ticks suit only the smallest parts. The kernel handles the wrap internally, with two timer lists, one for expiries in the current epoch and one for those after the overflow. Your own code must handle it too: compare tick counts by subtraction cast to a signed type, never by <.

wrap.cc
static int deadline_passed(TickType_t now, TickType_t deadline)
{
    return (int32_t)(now - deadline) >= 0;     /* correct across the wrap */
}

A direct comparison now >= deadline fails once now has wrapped past zero while deadline is still large. The same rule applies to xTimerGetExpiryTime().

A worked example: debounce, timeout and heartbeat

Three real timer jobs show the pieces working together. A device has a button that bounces, a request that must receive a reply within 500 ms, and a status LED that blinks to show the firmware is alive.

app_timers.cc
#include <stdio.h>
#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"

static TimerHandle_t s_debounce;    /* one-shot: confirm a press after it settles */
static TimerHandle_t s_replyWait;   /* one-shot: no reply arrived in time */
static TimerHandle_t s_heartbeat;   /* auto-reload: blink */

static void debounce_cb(TimerHandle_t t)
{
    (void)t;
    if (gpio_button_is_down()) {
        printf("[%lu] button press confirmed\n", (unsigned long)xTaskGetTickCount());
        request_send();
        xTimerStart(s_replyWait, 0);
    }
}

static void reply_timeout_cb(TimerHandle_t t)
{
    (void)t;
    printf("[%lu] no reply, giving up\n", (unsigned long)xTaskGetTickCount());
}

static void heartbeat_cb(TimerHandle_t t)
{
    (void)t;
    gpio_led_toggle();
}

void BUTTON_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;
    clear_button_interrupt();
    xTimerResetFromISR(s_debounce, &woken);       /* every edge restarts the 20 ms wait */
    portYIELD_FROM_ISR(woken);
}

void reply_received(void)                          /* called when the reply arrives */
{
    xTimerStop(s_replyWait, 0);
    printf("[%lu] reply ok\n", (unsigned long)xTaskGetTickCount());
}

void app_timers_start(void)
{
    s_debounce  = xTimerCreate("deb",  pdMS_TO_TICKS(20),  pdFALSE, NULL, debounce_cb);
    s_replyWait = xTimerCreate("rep",  pdMS_TO_TICKS(500), pdFALSE, NULL, reply_timeout_cb);
    s_heartbeat = xTimerCreate("beat", pdMS_TO_TICKS(500), pdTRUE,  NULL, heartbeat_cb);
    configASSERT(s_debounce && s_replyWait && s_heartbeat);
    xTimerStart(s_heartbeat, 0);
}

Each timer plays a distinct role, and each uses a different call. The debounce is a reset timer: every bouncing edge calls xTimerResetFromISR(), which restarts the 20 ms wait from now, so the callback fires only once the button has been quiet for 20 ms. The reply wait is a start and stop timer: it starts when the request goes out and xTimerStop() cancels it when the reply arrives, so the callback fires only on a miss. The heartbeat is a plain auto-reload timer.

With a button that bounces three times starting at tick 1,000, and a reply that never arrives, the console shows:

Text
[1031] button press confirmed
[1531] no reply, giving up

The last bounce was at about tick 1,011, so the debounce fired 20 ticks later; the exact tick depends on when the last edge occurs. The reply timeout fires 500 ticks after the confirmation. If reply_received() had been called at tick 1,200, the timeout callback would never have run, and the output would have been [1200] reply ok instead.

Notice how little code this is, and how few resources: three small control blocks and no extra stacks. A task per job would cost three stacks. That economy is the case for timers.

Reading your design for power

Tickless idle saves energy only if the system is idle for long stretches, so the work before enabling it is a review of everything that wakes the core. A short checklist:

  1. List every periodic timer and its period. Any period under configEXPECTED_IDLE_TIME_BEFORE_SLEEP plus the wake-up overhead prevents sleep. Combine housekeeping timers into one with a common period, or make them event-driven.

  2. List every task that polls. A task with vTaskDelay(1) in a loop never lets the system idle. Replace the poll with a blocking wait on a notification or a queue.

  3. List every interrupt that fires regularly. An ADC that samples at 1 kHz wakes the core 1,000 times a second regardless of the tick. Use the ADC's hardware triggers and DMA so the CPU sleeps through the conversions.

  4. Check the sleep mode. Deeper modes save more energy and take longer to leave. Pick the mode against your required wake-up latency, and confirm which clocks and peripherals keep running.

  5. Check the wake-up timer. In the sleep mode you chose, which timer still runs and is it the one the port uses to end the sleep?

  6. Measure with the probe disconnected. A debug probe distorts the current reading.

The last item deserves emphasis. Power is a measured quantity, and the only reliable measurement is with a current meter on the supply rail while the real firmware runs in the real mode. This guide does not give figures for savings because they depend on the part and the design, and any number quoted for another chip is not a prediction for yours.

Migrating polling loops to timers and events

Many codebases arrive with a superloop or a task with a delay loop that polls. The migration to timers and blocking is mechanical:

  1. A loop that does something every N ms and has no state between iterations becomes an auto-reload timer whose callback hands off to a task, or does the work directly if it is short.

  2. A loop that waits for a flag from an interrupt becomes a blocked task woken by a notification, as in the event groups and notifications guide.

  3. A loop that implements a timeout by counting iterations becomes a one-shot timer started with the operation and stopped on completion.

  4. A loop that debounces by sampling becomes a reset timer, as in the example above.

Do the conversion one loop at a time and keep the system running between steps. After each step the idle time grows, and with tickless idle enabled the device spends it asleep.

Software timers, tasks and hardware timers compared

NeedBest fitWhy
Run a short function after a delaySoftware timerNo stack, no task, a few bytes of control block
A repeating action with its own state and long stepsTask with vTaskDelayUntil()Own stack, may block
Sub-millisecond precision or a hard deadlineHardware timer interruptThe software timer is tick-resolution and late-prone
Timeout that is cancelled when a response arrivesSoftware timer with xTimerStop()Cheap to create, start, reset and stop
Measure elapsed timeA free-running counterNot a timer's job
Background work with no timingIdle hook or a low-priority taskNo period needed
Sleep through idle timeTickless idleRemoves the periodic wake-ups

The tick resolution is the central limit of a software timer. A timer set for 5 ms at a 1,000 Hz tick fires within the tick that contains 5 ms, with a one-tick uncertainty, and later if the timer task is blocked by a higher-priority task. For anything tighter, use a hardware timer's interrupt and notify a task.

Debugging timers

When a timer does not fire, check in order:

  1. Was it started? A created timer is dormant. xTimerIsTimerActive() returns pdFALSE for a dormant or stopped timer.

  2. Did the start command succeed? Check the return value of xTimerStart(). A pdFAIL means the command queue was full.

  3. **Is configUSE_TIMERS 1 and is the scheduler running?** Without the timer task, commands accumulate in the queue and nothing runs.

  4. Is the timer task starved? If a higher-priority task never blocks, the timer task never runs. Check configTIMER_TASK_PRIORITY against your tasks.

  5. Did a callback block? A blocked callback stops everything behind it. Look at the timer task's state in a kernel-aware debugger.

timer_debug.cc
void report_timer(TimerHandle_t t)
{
    printf("%s: %s, period %lu ticks, expires at %lu\n",
           pcTimerGetName(t),
           xTimerIsTimerActive(t) ? "active" : "dormant",
           (unsigned long)xTimerGetPeriod(t),
           (unsigned long)xTimerGetExpiryTime(t));
}
Text
poll: active, period 400 ticks, expires at 1050

xTimerGetPeriod() returns the period in ticks and xTimerGetExpiryTime() returns the tick count at which the timer will next expire. They give you the view of the timer list that the debugger would show.

Who this guide does not fit

Multicore parts. On an SMP kernel, the timer service task is one task that may run on any core, and tickless idle needs per-core handling. Read the SMP notes before depending on the behavior described here.

Hard real-time deadlines. A software timer callback is late if a higher-priority task is running, and it is subject to the tick resolution. Use a hardware timer interrupt for deadlines.

Deep-sleep designs. The default tickless implementation assumes a sleep mode in which SysTick keeps running. If your lowest-power mode stops it, you must write the suppress-and-sleep function around a low-power timer.

Safety-certified builds. If your project uses a qualified kernel, confirm that timers and tickless idle are part of the qualified feature set.

If your timers need to detect missing messages, read the watchdog-style timeout post. To understand how the kernel decides how long it can sleep, the idle-time calculation is in the post on how tick suppression calculates the expected idle time, and the power measurement approach is in the tickless power profiling post. The kernel source is short and readable: timers.c holds the whole timer service task, and the idle loop is in tasks.c.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.