我正在对 Arduino Mega 克隆进行编程,因此我的主板使用的是 ATMEGA2560,我的代码位于 Arduino 框架中。
我试图在中断模式下启用看门狗,以便我可以调用自定义 ISR,但我发现看门狗超时未使用我设置的值(8 秒)。
这是我的代码:
void setupWatchdog(uint8_t timeout) {
cli();
// Avoid eternal loop of time-out resets by clearing WDRF
MCUSR &= ~(1<<WDRF);
// Reset watchdog timer
wdt_reset();
// Enable WD timer configuration mode
WDTCSR |= 1 << WDCE | 1 << WDE;
// Reset WD timer
WDTCSR = 0;
// Configure period
wdt_enable(WDTO_1S);
// Use WD timer in interrupt mode
WDTCSR |= 1 << WDIE;
sei();
}
ISR(WDT_vect) {
Serial.println(F("Watchdog Timer Interrupt"));
// Re-enable watchdog timer interrupt to avoid reset
WDTCSR |= 1 << WDIE;
}
void setup() {
setupWatchdog(WDTO_8S);
}
void loop() {
while (true);
}
我的期望是 ISR 应每约 8 秒打印一次,但它只是连续打印。第一次打印甚至不需要等待 8 秒,就直接开始连续打印。我错过了什么?
在
setupWatchdog()
中,无论 timeout
参数如何,都将看门狗初始化为 1 秒:
// Configure period
wdt_enable(WDTO_1S);
应该是
// Configure period
wdt_enable(timeout);