I've been trying to track down a sporadic error for a few days now. I've set up the watchdog timer sucessfully, but every now and then it fails to restart the MCU. Sometimes it restarts 20 times in a row without problems, but other times it fails to restart at all. This seems to depend a bit on the size of the sketch (the biggest version of the sketch is 160kByte), but that may be only random coincidence.
Let me mention all the things that DON'T influence this sporadic error: - it doesn't matter if I set the timeout period to something small like 1 second, or to 8 seconds. - it doesn't matter if a watchdog interrupt is set up or not. - it doesn't matter if the USB cable is connected to the PC or not.
If the watchdog interrupt is enabled, the interrupt will always execute flawlessly, but the reset remains flakey. A power off/on reset always brings the application code back to life.
The WDE bit inside the WDTCSR byte is always correct and not accidentally modified by other parts of the code - I checked this by Serial.printing this bit inside the interrupt function.
This issue is consistent across the original Arduino Mega Rev3, the new Genuino Mega, and a Sainsmart Mega. On the Sainsmart, I re-flashed the bootloader, but no difference.
The arduino is currently used naked, with no external hardware attached at all, so external hardware can't be the reason either.
Now I'm aware that nobody will be able to magically give me the solution to this issue. Google tells me that the watchdog on the mega was not functioning, until the stk500boot_v2_mega2560.hex bootloader came out in 2012. But since then, there's no real hot lead anymore.
But maybe someone can point me in the right direction, how to proceed further. So far my thinking goes this way: It can't really be caused by a bug in my application code - and even if, the whole point of the watchdog is to reset the system in case of a bug in the code. I also assume ATMEL produces a mcu with an actually functioning watchdog.
So, the only place left to look is the bootloader, as far as I understand it. This is unexplored territory for me. I found the C code for the bootloader in C:\Program Files (x86)\Arduino\hardware\arduino\avr\bootloaders\stk500v2\stk500boot.c
How do I compile this into an hex file? (I have a windows 10 PC and arduino 1.6.3)
From there on, I would use the built in IDE functions to upload the hex file. I've done this already with another mega as ISP, with the "Arduino as ISP" sketch from the IDE.
Second question: how can I Serial.print debugging information, while the bootloader code is executing?
Or are there other bootloaders for the mega around? Optiboot seems to be popular, but doesn't work with the mega.
Thank you Thomas