yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
ESP32 Core Board📖
1. ESP32 Introduction
  • 1. ESP32S3 Overview
  • 2. Environment Setup Introduction
  • 3. Dev Board Introduction
2. ESP-IDF Development Tutorial
1. Before Development
  • 1. Environment Setup (Windows)
  • 2. Environment Setup (Linux)
  • 3. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. DMA
  • 8. ADC
  • 9. PWM Breathing LED
  • 10. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. PSRAM External Memory Experiment
  • 5. Flash Read and Write Experiment
  • 6. USB Emulated Mass Storage Experiment
4. FreeRTOS operating system
  • 1.FreeRTOS Core Concepts Theory
  • 2.Task Creation and Management
  • 3.Queue
  • 4.Binary Semaphore
  • 5.Mutex
  • 6.Event Groups
  • 7.Software Timer
  • 8.Task Scheduler
  • 9.Low Power Mode
  • 10.Deadlock
  • 11.Priority Inversion
5. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. Socket Programming Basics
  • 9. HTTP Client Experiment
  • 10. HTTP Server Experiment
  • 11. MQTT IoT Communication Protocol
  • 12. WIFI OTA Upgrade
  • 13. Bluetooth Fundamentals
  • 14. Bluetooth Slave Mode
  • 15. Bluetooth Master Mode
6. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
7. Xiaozhi AI Voice
  • 1. Burn Xiaozhi Firmware
  • 2. Network and Configuration
  • 3. AI Agent Settings
  • 4. Program Analysis
  • 5. Free Chat
3. Arduino Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. ADC
  • 8. PWM Breathing LED
  • 9. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication
  • 2. I2C OLED Display
  • 3. SPI Bus Communication
  • 4. Flash Read and Write
  • 5. USB Emulated Mass Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Server Experiment
  • 5. UDP Client Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT IoT Communication Protocol
  • 11. WIFI OTA Upgrade
  • 12. Bluetooth Fundamentals
  • 13. Bluetooth Slave Mode
  • 14. Bluetooth Master Mode
5. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
4. MicroPython Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
  • 3. Thonny IDE
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. TIMER_IT
  • 5. Watchdog Timer
  • 6. ADC
  • 7. PWM Breathing LED
  • 8. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. Flash Read and Write Experiment
  • 5. Print Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT
  • 11. Bluetooth Fundamentals
  • 12. Bluetooth Slave Mode
  • 13. Bluetooth Master Mode
5. Audio Applications
  • 1. I2S Audio Playback Experiment
  • 2. Repeater Experiment
Download
  • Code
  • Hardware_Info
  • 3D_Model_File
  • Software_Tools
  • VMware
  • VM_File
Download ZIP

Welcome to ESP32 Core Board repository

6. Watchdog Timer

Watchdog Timer


Watchdog Timer1. Watchdog OverviewHow Important is the Watchdog? Real-World Lessons2. Core Concepts2.1 Watchdog Principle2.2 Non-Blocking Delay2.3 millis() Overflow Handling3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Details5.1 Macros and Global Variables5.2 Feed and Timeout Detection5.3 Non-Blocking Delay + Button Detection5.4 setup() — Three-Phase Demo6. Operation Flow6.1 Build and Flash6.2 Normal Behavior6.3 Boundary Tests7. Common Issues


1. Watchdog Overview

Watchdog Timer (WDT) is a fault tolerance mechanism: the program must "feed the dog (reset)" within a specified time, otherwise the watchdog determines the system is frozen and automatically resets. This experiment uses software to simulate a watchdog, demonstrating in three phases: automatic feeding (normal operation) → stop feeding (simulating freeze) → timeout reset. The reason for using software simulation instead of hardware WDT is that hardware WDT resets too fast to print debug information; software simulation allows clear observation of the entire process.

Typical Application Scenarios:

Application TypeExample
Industrial ControlPLC freeze protection, production line controller automatic recovery
Remote DevicesUnattended base stations, outdoor smart meters (electricity/water)
Communication EquipmentRouter/gateway deadlock auto-reset
Medical/AutomotivePatient monitors, infusion pumps, automotive ECU (mandatory safety certification)
Smart HomeCeiling-mounted gateways, smart locks (unreachable by humans, can only self-recover)

How Important is the Watchdog? Real-World Lessons

The watchdog is not a "premium feature" but the bottom line for survival of embedded products. Here are some real scenarios:

  • Industrial Controller (PLC): If one controller on the production line crashes, the entire assembly line stops. Losses could reach thousands of yuan per minute. With WDT, auto-restart recovers production within seconds; without WDT, you wait for a worker to run over and press the reset button. If no one is around, losses are tens of thousands of yuan per hour.

  • Smart Meters (Electricity/Water): Installed in outdoor pipe wells or on power poles. Once it crashes, no one knows. A month of data is lost. WDT is its only means of "self-rescue."

  • Drone Flight Controller: If the program runs away while flying, no WDT means free fall; with WDT, the flight controller can at least restart instantly and switch to safe mode for landing.

  • Medical Equipment: If a patient monitor or infusion pump crashes, it's not a "just restart it" problem. It's a matter of life and death. WDT is a mandatory requirement for medical certification.

  • Automotive ECU: The engine control unit crashes while driving? Without WDT, you don't even want to think about it. So automotive-grade MCU watchdogs use independent clock sources, completely decoupled from the main CPU.

  • Smart Home Gateway: Installed in ceiling cavities. If it crashes, humans can't reach it. Without WDT, it's just a brick. Users can only power cycle it. Terrible experience.

In short: As long as your device is not connected to a debugger everywhere you go, you should enable the watchdog. The watchdog is not used to prevent bugs, but to prevent the consequences of bugs — device becoming a brick, production lines stopping, even casualties. It's a "worst-case insurance."


2. Core Concepts

2.1 Watchdog Principle

​x
Normal Flow: Program periodically "feeds the dog" (resets counter)
             feed() → feed() → feed() → ...

Abnormal Flow: Program freezes → Stop feeding → Counter overflow → System reset

This experiment uses millis() and last_feed_time variable to simulate the hardware watchdog counter mechanism: millis() - last_feed_time > 5s determines timeout.

2.2 Non-Blocking Delay

The program needs to continuously check buttons and timeout while waiting, without using delay(). This experiment uses delay_check_button() function to split long delays into 20ms fragments, checking button and timeout once per fragment:

xxxxxxxxxx
while (not time yet) {
    if (button pressed) feed;
    if (timeout) return;
    delay(20ms);  // short fragment wait
}

2.3 millis() Overflow Handling

millis() returns unsigned long, which will overflow back to 0 after approximately 49 days. Using unsigned subtraction is naturally immune to overflow:

xxxxxxxxxx
millis() - last_feed_time > WDT_TIMEOUT_MS

Even at overflow boundaries (e.g., millis()=100, last_feed_time=4294967200), unsigned subtraction's modulo arithmetic still gives the correct difference. This is a classic technique in embedded systems.


3. Hardware Dependencies

PinPeripheralConfigurationDescription
GPIO0BOOT ButtonINPUT_PULLUPPress = low level, used for manual feed

4. Project Architecture and Flow

xxxxxxxxxx
setup()
  ├─ Initialize serial + button
  ├─ feed_watchdog()          // Initial feed
  │
  ├─ Phase 1: Auto Feed        // Simulate normal operation
  │    └─ for i=1..5:
  │         feed() + delay_check_button(1000ms)
  │
  ├─ Phase 2: Stop Feed        // Simulate freeze
  │    └─ Countdown 3 seconds, BOOT can extend feed during this time
  │
  └─ Phase 3: Timeout Reset
       └─ ESP.restart()

delay_check_button(ms)         // Non-blocking wait
  └─ while (not ms yet):
       ├─ BOOT pressed? → feed() + wait for release → return 1
       └─ Timeout? → return 2

5. Source Code Details

Full source code: Source Code → Arduino → 1.Basic Peripherals → 6.Watch_Dog → 6.Watch_Dog.ino

5.1 Macros and Global Variables

Configure watchdog timeout, feed count, countdown and other parameters, all centralized in macros for easy adjustment.

xxxxxxxxxx
#define BOOT_PIN         0
#define FEED_COUNT       5           // Phase 1 auto feed 5 times
#define FEED_INTERVAL_MS 1000        // 1s interval between feeds
#define COUNTDOWN_SEC    3           // 3s countdown after stopping feed
#define WDT_TIMEOUT_MS   5000        // 5s without feed = timeout

unsigned long last_feed_time = 0;    // Last feed timestamp
bool wdt_enabled = true;

5.2 Feed and Timeout Detection

feed_watchdog() records the timestamp; "feeding the dog" means telling the watchdog "I'm still alive". watchdog_timeout() checks for timeout.

xxxxxxxxxx
void feed_watchdog() {
  last_feed_time = millis();
}

bool watchdog_timeout() {
  return wdt_enabled && (millis() - last_feed_time > WDT_TIMEOUT_MS);
}

millis() - last_feed_time uses unsigned subtraction, still correct even crossing the ~49 day overflow point.

5.3 Non-Blocking Delay + Button Detection

This is the core of the entire experiment — splitting long delays into 20ms fragments while maintaining real-time responsiveness.

xxxxxxxxxx
int delay_check_button(unsigned long ms) {
  unsigned long start = millis();

  while (millis() - start < ms) {
    if (digitalRead(BOOT_PIN) == LOW) {        // Button pressed → manual feed
      feed_watchdog();
      while (digitalRead(BOOT_PIN) == LOW) delay(10);  // Wait for release
      return 1;                                  // Return: manual feed
    }

    if (watchdog_timeout()) return 2;            // Return: WDT timeout
    delay(20);                                   // 20ms check interval
  }
  return 0;                                      // Return: normal timeout
}

The three return values correspond to three events: nothing happened / manual feed / timeout. The caller decides subsequent actions based on the return value.

5.4 setup() — Three-Phase Demo

All logic runs once in setup(), loop() is left empty.

xxxxxxxxxx
void setup() {
  Serial.begin(115200);
  pinMode(BOOT_PIN, INPUT_PULLUP);
  feed_watchdog();

  // === Phase 1: Auto Feed ===
  for (int i = 1; i <= FEED_COUNT; i++) {
    feed_watchdog();
    Serial.printf("[WDT] Auto Feed #%d/%d\n", i, FEED_COUNT);
    if (delay_check_button(FEED_INTERVAL_MS) == 2) break;
  }

  // === Phase 2: Stop Feed ===
  int countdown = COUNTDOWN_SEC;
  while (countdown > 0) {
    int ret = delay_check_button(1000);
    if (ret == 1) { countdown = COUNTDOWN_SEC; }  // BOOT pressed → reset countdown
    else if (ret == 2) { break; }                  // Timeout → enter Phase 3
    else { countdown--; }
  }

  // === Phase 3: Reset ===
  Serial.println("\n[WDT] Watchdog timeout! Resetting...");
  ESP.restart();
}

void loop() {}

Pressing BOOT in Phase 2 resets the countdown — equivalent to "rescuing" a frozen system, demonstrating the typical interaction pattern for manual watchdog intervention.


6. Operation Flow

6.1 Build and Flash

Arduino flash process: See Arduino → 1. Before Development → 2. Build and Flash.

6.2 Normal Behavior

Open the Serial Monitor (115200 bps) and observe the three phases:

  • Phase 1: Auto feed once every 1 second, 5 times total

  • Phase 2: Stop feeding, 3 second countdown. Press BOOT to reset countdown

  • 串口打印

  • Phase 3: Timeout, chip restarts after printing "Resetting..."

Watchdog Reset

6.3 Boundary Tests

Test CaseOperationExpected Result
No button pressDon't touch BOOT at allPhase 1 → Phase 2 → 3 second countdown → Reset
Press BOOT during Phase 2Press once every 2 secondsCountdown repeatedly resets, system doesn't restart
Long press BOOTHold BOOT during Phase 2One feed + wait for release, countdown resets once

7. Common Issues

SymptomCauseSolution
Resets in Phase 2 without timeoutCountdown logic or delay_check_button timeout detection conflictCheck return value handling
Continuous feeding when button heldNot waiting for releaseConfirm while (digitalRead(BOOT_PIN) == LOW) delay(10) exists
Garbled serial outputBaud rate mismatchConfirm monitor set to 115200
GPTIMER
ADC

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文