Home / Learn Chip Programming / RTC and Watchdog Timers
RTC and Watchdog Timers
Keep real time across power loss, and recover automatically from hangs.
Theory in plain words
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
Tick the hang box: the counter is no longer reset and reaches the timeout, which resets the chip. With normal kicks it never expires.
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();
}
}| Part | Detail |
|---|---|
| RTC crystal | 32.768 kHz watch crystal: divides to exactly 1 Hz (2^15) |
| Backup | CR2032 coin cell on VBAT: runs ~5 years |
| DS3231 | I2C RTC with temperature compensated crystal, +/- 2 ppm |
| Window watchdog | must be kicked inside a window, catches runaway loops too |
| Reset reason register | check it at boot: power-on, watchdog or brown-out? |
Quick quiz
1. Why 32.768 kHz?
A 15 bit counter overflows once per second.
2. Where should you kick the watchdog?
It must prove the program is really working.
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.