2

I want to trigger a soft reset on my Arduino Leonardo, and after some searching settled on using the watchdog timer, as it seemed to be the easiest and cleanest way to do it.

However, I don't think it works as it should. It seems to work fine on the following example:

#include <avr/wdt.h>

int outputPin = LED_BUILTIN;

void setup() {
  MCUSR = 0;
  wdt_disable();
  pinMode(outputPin, OUTPUT);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(500);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(1000);
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

The LED blinks continuously,.

But for the following example:

#include <avr/wdt.h>

void setup() {
  MCUSR = 0;
  wdt_disable();
  Serial.begin(9600);
  while (!Serial);
  Serial.println("Hello");
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

"Hello" only gets printed once (where I would expect it to arrive continuously).

I tried increasing the watchdog timeout to 2 seconds, but that didn't solve the issue.

  • try for a test a longer time, for example WDTO_2S. some bootloaders don't reset the wdt flag and then the next reset is triggered before the chip enters your setup(). – Juraj Nov 29 '18 at 9:42
  • @Juraj changing WDTO_15MS to WDTO_2S in the above example only causes the final state (L on, RX blinking) to set in 2 seconds later, unfortunately it didn't solve the problem. – martonbognar Nov 29 '18 at 9:53
  • you test with a sketch without Serial like the sketch in the Question? – Juraj Nov 29 '18 at 10:22
  • Hint: You could define a function to the reset-vector, e.g. void (*RESET)() = NULL; and then call the function when wanted, e.g. RESET();. Please note that all hardware registers are not reset. The sketch setup should not assume a hardware register state. – Mikael Patel Nov 29 '18 at 11:06
  • @Juraj I edited the question. I have since discovered that I was missing pinMode from my original example, and that solved that specific issue. However, for the (now added) Serial example it still doesn't work. – martonbognar Nov 29 '18 at 11:07
1

So it turns out my code was working correctly, the watchdog performed the reset as it should, the problem was only that I needed to relaunch the serial monitor after each reset.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.