Home / Learn Chip Programming / RTC and Watchdog Timers

RTC and Watchdog Timers

Keep real time across power loss, and recover automatically from hangs.

In shortKeep real time across power loss, and recover automatically from hangs.

Theory in plain words

WatchdogStart watchdog (timeout 1 s)main loop works, kickssoftware hangsno kick within 1 shardware reset, device recovers
Watchdog

What it is

An RTC (real time clock) counts seconds from a 32.768 kHz crystal, often on a backup battery. A watchdog resets the chip if the firmware does not "kick" it in time.

Why we use it

Data loggers need timestamps. Unattended devices (remote sensors, machines) must recover without a human if software hangs.

How it works

Set the RTC time once, read BCD registers. Configure the watchdog timeout, then feed it only from the healthy main loop, never from a timer ISR alone.

Where it is used

  • DS3231 RTC logs
  • STM32 IWDG / ESP32 TWDT
  • Reliability in field devices

Watchdog simulator

Will the dog bite?Try it Yourself

Tick the hang box: the counter is no longer reset and reaches the timeout, which resets the chip. With normal kicks it never expires.

Watchdog pattern
int main(void) {
    init();
    wdt_enable(2000);                       // 2 s timeout
    for (;;) {
        if (task_a_ok() && task_b_ok() && comm_alive())   // check each subsystem is healthy
            wdt_kick();                                    // only then reset the counter
        do_work();
    }
}
PartDetail
RTC crystal32.768 kHz watch crystal: divides to exactly 1 Hz (2^15)
BackupCR2032 coin cell on VBAT: runs ~5 years
DS3231I2C RTC with temperature compensated crystal, +/- 2 ppm
Window watchdogmust be kicked inside a window, catches runaway loops too
Reset reason registercheck it at boot: power-on, watchdog or brown-out?
Careful:Do not kick the watchdog from a timer interrupt: the ISR keeps running even if main is stuck and the dog never bites.

Quick quiz

1. Why 32.768 kHz?

2. Where should you kick the watchdog?

Common questions

Why 32.768 kHz?

2^15 divides to exactly 1 Hz. A 15 bit counter overflows once per second.

Where should you kick the watchdog?

In the main loop after health checks. It must prove the program is really working.