Skip to content
systemcoding.dev
RTOS

Build a Watchdog-Style Timeout by Restarting a Timer With xTimerReset

Detect a lost heartbeat in FreeRTOS by resetting a one-shot software timer on every message, with the timeout callback, ISR resets and per-link supervision.

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

A sensor sends a reading every 100 ms. If 500 ms pass with nothing, the system should mark the sensor as lost, switch to a fallback and tell someone. Polling a "last seen" timestamp from a loop does it, at the price of a loop. A cheaper structure is a one-shot software timer that you restart on every message: as long as readings keep arriving, the timer never gets to expire, and the moment they stop, it fires. This is the same idea as a hardware watchdog, applied to one link in software, and xTimerReset() is the call that makes it work. This post builds it on FreeRTOS kernel V11.1.0: the reset-on-message pattern, the timeout callback, resets from an interrupt, supervising several links with one callback, and the limits compared with a hardware watchdog. The timer calls are introduced in the xTimerCreate post.

The idea

A one-shot timer with a period equal to the timeout is created, but never allowed to expire while the link is healthy. Every time a message arrives, the receiver calls xTimerReset(), which restarts the full period from now. If messages stop, no reset happens, the period runs out, and the timer's callback runs. The callback is therefore "the link went silent".

xTimerReset() has two properties that suit this. It restarts a running timer, pushing its expiry out, and it also starts a timer that is stopped, so the same call arms the supervision on the first message without a separate start.

The code

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

#define LINK_TIMEOUT_MS 500

static TimerHandle_t s_linkTimer;
static volatile BaseType_t s_linkUp;

static void link_lost_cb(TimerHandle_t t)
{
    (void)t;
    s_linkUp = pdFALSE;
    printf("[%lu] sensor link lost\n", (unsigned long)xTaskGetTickCount());
    switch_to_fallback();
}

void link_watch_init(void)
{
    s_linkTimer = xTimerCreate("linkwd", pdMS_TO_TICKS(LINK_TIMEOUT_MS), pdFALSE, NULL, link_lost_cb);
    configASSERT(s_linkTimer != NULL);
}

void sensor_message_received(void)               /* called from the receiver task */
{
    if (s_linkUp == pdFALSE) {
        s_linkUp = pdTRUE;
        printf("[%lu] sensor link up\n", (unsigned long)xTaskGetTickCount());
    }
    xTimerReset(s_linkTimer, 0);                 /* push the deadline 500 ms out */
}

The timer is a one-shot, so after it fires once it stays quiet instead of repeating "lost" messages. The first message arms it and reports the link as up. Subsequent messages only reset it.

A run with messages at 100, 200 and 300 ms and then silence:

Text
[100] sensor link up
[800] sensor link lost

The last reset was at tick 300, so the timer expired 500 ticks later, at 800. If a message arrives at 900 afterwards, sensor_message_received() prints "link up" and the reset starts the timer again, so one watchdog covers any number of outages.

Resetting from an interrupt

If the messages arrive in an interrupt, use xTimerResetFromISR():

link_isr.cc
void USART3_IRQHandler(void)
{
    BaseType_t woken = pdFALSE;

    if (USART3->SR & USART_SR_IDLE) {                /* a frame ended */
        (void)USART3->DR;
        s_linkUp = pdTRUE;
        xTimerResetFromISR(s_linkTimer, &woken);
    }
    portYIELD_FROM_ISR(woken);
}

The call sends a command to the timer queue and returns at once. If the queue is full, the reset is lost, and the timer may fire although the link is healthy. For a link that sends messages faster than the timer task drains its queue, that is a real risk: a burst of many resets per tick fills the queue. Reset only once per message batch, or rate-limit the resets, for example by resetting only if the last reset was more than 10 ms ago, using a tick comparison.

The reset command is stamped with the tick at which it was sent, so processing delay does not shorten the timeout: the expiry is the tick of the reset plus the period.

A system with a sensor, a radio and a display link can use one callback and give each timer an identifier:

multi_link.cc
typedef struct {
    const char *name;
    volatile BaseType_t up;
} link_t;

static link_t s_links[3] = {
    { "sensor",  pdFALSE },
    { "radio",   pdFALSE },
    { "display", pdFALSE },
};
static TimerHandle_t s_timers[3];

static void any_link_lost(TimerHandle_t t)
{
    link_t *l = pvTimerGetTimerID(t);
    l->up = pdFALSE;
    printf("[%lu] %s link lost\n", (unsigned long)xTaskGetTickCount(), l->name);
}

void links_init(void)
{
    const uint32_t timeouts_ms[3] = { 500, 2000, 1000 };
    for (int i = 0; i < 3; i++) {
        s_timers[i] = xTimerCreate(s_links[i].name, pdMS_TO_TICKS(timeouts_ms[i]),
                                   pdFALSE, &s_links[i], any_link_lost);
        configASSERT(s_timers[i] != NULL);
    }
}

void link_alive(int index)
{
    s_links[index].up = pdTRUE;
    xTimerReset(s_timers[index], 0);
}

Each link has its own timeout, and one callback handles all of them by reading the structure from the timer ID. The cost is three timer control blocks and one function, with no polling loop and no task.

If link_alive(0) is called at 100 and the sensor then stops, and link_alive(1) is called at 150 and the radio stops:

Text
[600] sensor link lost
[2150] radio link lost

The expiry times differ because the periods differ: 100 plus 500, and 150 plus 2,000.

Starting the supervision

You decide when supervision begins. Two choices:

Start on the first message. As above, xTimerReset() on a stopped timer starts it. Nothing is supervised until the link has spoken once. That suits a link that may be absent on some units.

Start at boot. Call xTimerStart() once in the init function. If the link never speaks, the timer fires after the timeout, and the "lost" path runs. That suits a link that must always be present, because silence from boot is a fault.

boot_start.cc
void link_watch_start_at_boot(void)
{
    xTimerStart(s_linkTimer, 0);                 /* absent from boot counts as lost */
}

Adding hysteresis

A link that flaps, with a message just inside the timeout and then a long gap, can generate "up" and "lost" events repeatedly. Add a small rule: require N consecutive messages before declaring the link up again.

hysteresis.cc
#define UP_AFTER 3

static uint32_t s_consecutive;

void sensor_message_received2(void)
{
    if (s_linkUp == pdFALSE) {
        if (++s_consecutive >= UP_AFTER) {
            s_linkUp = pdTRUE;
            s_consecutive = 0;
            printf("[%lu] sensor link up\n", (unsigned long)xTaskGetTickCount());
        }
    }
    xTimerReset(s_linkTimer, 0);                 /* still reset on every message */
}

static void link_lost_cb2(TimerHandle_t t)
{
    (void)t;
    s_consecutive = 0;
    s_linkUp = pdFALSE;
    printf("[%lu] sensor link lost\n", (unsigned long)xTaskGetTickCount());
}

The counter is written from the receiver task and from the timer callback, in two different tasks. For a simple counter that is acceptable if both writes are single instructions and the order does not matter much; for anything stronger, guard it with a short critical section.

Limits compared with a hardware watchdog

PropertySoftware timer watchdogHardware watchdog
Detects a silent linkYesNot directly
Detects a hung processorNo, it relies on the timer task runningYes, it resets the chip
Survives a crash of the kernelNoYes
CostA timer control blockA peripheral
ResolutionOne tick, plus timer task latencySet by the watchdog clock
What it does on timeoutRuns a callback you writeResets the device

A software timeout is a supervision tool for a link or a task, not a safety net for the processor. If the timer task itself is stuck, because a callback blocked or a higher-priority task never yields, the timer never fires, and nobody notices. Keep the independent hardware watchdog for the "the whole system is dead" case, and use timer-based timeouts for the "that peer went quiet" case. A good structure feeds the hardware watchdog from a supervisory task that checks the software timeouts, so the hardware watchdog resets the device if the supervisor itself stops.

Mistakes to avoid

**Using xTimerStart() on every message.** On a running timer it does not move the expiry, so the timer fires on schedule although messages kept arriving. Use xTimerReset().

A period shorter than the message interval. If messages arrive every 100 ms and the timeout is 80 ms, the timer fires between every pair. Make the timeout several message intervals long, to tolerate a lost or late one. A common rule is three to five intervals.

A blocking callback. The timeout callback runs in the timer service task. Do the quick part there, and notify a task for anything else.

Flooding the command queue. Resetting at a high rate from an interrupt can fill configTIMER_QUEUE_LENGTH. Reset per batch, not per byte.

**Forgetting configUSE_TIMERS.** Without it the calls do not exist. The build fails, which is the good outcome.

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.