watchdog.c

nRF52840-MDK (boards.json id: nrf52840-mdk) · File : watchdog.c · Language : C · Use case : Surveiller le programme avec le watchdog matériel

The nRF52840 WDT resets the chip unless the firmware feeds its channel in time: frozen loops, deadlocks and software stalls become automatic reboots. Essential inside a sealed enclosure.

Hardware

An nRF52840-MDK board (Nordic nRF52840, Cortex-M4F @ 64 MHz, 1 MB flash / 256 KB RAM, BLE 5 + 802.15.4) with onboard debugger, programmed in C with nRF5 SDK v17 and the S140 SoftDevice. nRF52840-MDK alone; an optional serial monitor to watch the reboots.

Wiring

No wiring; LED P0.06 as a life indicator (it freezes when the program does).

How it works

The allocated channel must be fed before timeout (~8 s); in RUN_SLEEP mode the timer keeps running during sleep. Expiry → system reset, execution restarts at main().

Running it

Open the matching nRF5 SDK v17 example (custom_board target), paste this code into main.c, build with Segger Embedded Studio or the gcc Makefile, then flash through the onboard debugger.

Variants

Feed the watchdog only when each subtask has run (fine supervision), or log the reset cause (PFFRESETREAS) to flash.

watchdog.c

// nRF52840-MDK : watchdog matériel WDT — reset si la boucle principale gèle.
#include "nrf_drv_wdt.h"
#include "nrf_delay.h"

static nrf_drv_wdt_channel_id canal;

void wdt_evt(void) { }        // optionnel : avertir avant reset (PPI/LPCOMP)

int main(void) {
  nrf_drv_wdt_config_t cfg = NRF_DRV_WDT_DEAFULT_CONFIG;
  cfg.behaviour = NRF_WDT_BEHAVIOUR_RUN_SLEEP;   // tourne aussi en sommeil
  cfg.timeout   = WDT_TIMEOUT;                    // 8x32768 ticks ~ 8 s (adapter)
  nrf_drv_wdt_init(&cfg, wdt_evt);
  nrf_drv_wdt_channel_alloc(&canal);
  nrf_drv_wdt_enable();

  uint32_t tour = 0;
  for (;;) {
    nrf_drv_wdt_channel_feed(canal);   // "j'ai tourné" — sans ça : reset
    tour++;
    nrf_gpio_pin_toggle(6);
    nrf_delay_ms(200);

    // Démo : bloquer volontairement au tour 50 pour voir le reset.
    if (tour == 50) { while (1) { } }
  }
}

← Back to the board