</>EmbeddedInterview

Write a watchdog service routine.

Easy"Coding: Embedded Drivers, Buffers & Schedulers"
#include <stdint.h>
#include <stdbool.h>

#define IWDG_KR (*(volatile uint32_t *)0x40003000u)      /* STM32 independent watchdog key register */
#define TASK_SENSOR (1u << 0)
#define TASK_COMMS  (1u << 1)
#define TASK_CTRL   (1u << 2)
#define ALL_ALIVE   (TASK_SENSOR | TASK_COMMS | TASK_CTRL)

static volatile uint32_t alive_flags;

void wdg_checkin(uint32_t task_bit)                      /* each task calls this when it completes a cycle */
{
    __atomic_fetch_or(&alive_flags, task_bit, __ATOMIC_RELAXED);
}

void wdg_service(void)                                   /* called periodically, e.g. every 100 ms */
{
    if ((alive_flags & ALL_ALIVE) == ALL_ALIVE) {
        IWDG_KR = 0xAAAAu;                               /* reload (kick) the watchdog */
        __atomic_store_n(&alive_flags, 0u, __ATOMIC_RELAXED);
    }
    /* else: do not kick; the watchdog resets the MCU */
}

Points: kick only when every critical task has proven it is running, not from a timer interrupt alone; use a window watchdog to also catch code that runs too fast; record the reset cause at boot; freeze the watchdog in debug halt. On Cortex-M0 (no atomic OR instructions) wrap the read-modify-write in a short critical section.